【Spring】注解器

发布时间 2023-04-03 09:20:29作者: 小鼻涕孩
applicationContext.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6       http://www.springframework.org/schema/beans/spring-beans.xsd
 7       http://www.springframework.org/schema/context
 8   http://www.springframework.org/schema/context/spring-context.xsd">
 9     <!-- 使用context命名空间,开启注解处理器 -->
10     <context:component-scan base-package="com.xiaobiti"/>
11 </beans>

新建../entity/User.java

 1 package com.xiaobiti.entity;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.context.annotation.Scope;
 5 import org.springframework.stereotype.Component;
 6 
 7 @Component("user")
 8 @Scope("singleton")//bean作用域单例模式
 9 public class User {
10     @Value("1")
11     private int id;//实例化给id赋值为1
12     @Value("张三")
13     private String name;//实例化给name赋值为张三
14     @Value("123")
15     private String password;//实例化给password赋值为123
16 
17     public int getId() {
18         return id;
19     }
20 
21     public void setId(int id) {
22         this.id = id;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public String getPassword() {
34         return password;
35     }
36 
37     public void setPassword(String password) {
38         this.password = password;
39     }
40 
41     @Override
42     public String toString() {
43         return "User{" +
44                 "id=" + id +
45                 ", name='" + name + '\'' +
46                 ", password='" + password + '\'' +
47                 '}';
48     }
49 }

@Repository  用于指定类为bean的数据访问层

@Service  用于指定类为bean的业务逻辑层

@Controller 用于指定类为bean的控制层