多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**1. 两大类的Bean注解** 下面是常用的Bean注解,Bean注解分成两大类:用于创建Bean的注解和用于属性注入的注解。 (1)用于创建Bean的注解 ```java @Component:是所有Spring注解的基石,后面见到的所有Spring注解都是基于该注解开发而来 @Repository:通常用于dao层 @Service:通常用于service层 @Controller:通常用于controller层 ``` (2)用于属性注入的注解 ``` @Autowired:根据类型自动装配 @Qualifier:必须与@Autowired一起使用,根据名字自动装配 @Resource:根据名字,或类型自动装配 @Value:用于对一个String类型的属性赋值 ``` <br/> **2. Bean注解的使用步骤** (1)在`resources/ApplicationContext.xml`中开启包扫描。 ```xml <?xml version='1.0' encoding='UTF-8'?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启包扫描,它可以扫描当前包及其子包;如果需要扫描多个包,可以使用 , 隔开--> <context:component-scan base-package="com.learn.spring06.*"/> </beans> ``` (2)在dao层中使用。 ```java /** * (1)如果是 @Repository ,则会自动创建 <bean id="studentDaoImpl class="xx.dao.impl.StudentDaoImpl"/> * (2)如果是 @Repository("studentDaoImpl2"),则会自动创建 <bean id="studentDaoImpl2 class="xx.dao.impl.StudentDaoImpl"/> * 其中@Component、@Service、@Controller也是一样的道理 */ @Repository public class StudentDaoImpl implements StudentDao { @Override public void printName(String name) { System.out.println(name); } } ``` (3)在service层中使用。 ```java @Service public class StudentServiceImpl implements StudentService { /** * (1)@@Autowired,根据类型自动装配,Spring会自动判断StudentDaoImpl是StudentDao类型,所以StudentDaoImpl将自动装配给该属性 * (2)@Qualifier与@Autowired 共同使用,实现按名字自动装配 */ @Autowired //@Qualifier("studentDaoImpl") private StudentDao studentDao; //@Resource 这样写则根据类型自动装配 //@Resource("studentDaoImpl") 这样写则根据名字自动装配 //private StudentDao studentDao; @Value(value = "张三") //自动将张三赋值给name属性 private String name; @Override public void printName(String name) { if (name == null) { studentDao.printName(this.name); } else { studentDao.printName(name); } } } ``` (4) 测试。 ```java @Test public void printName() { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); StudentService studentService = context.getBean(StudentService.class); studentService.printName(null); //张三 } ```