<?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:annotation-config/> </beans>
public class People { @Autowired private Dog dog; @Autowired private Cat cat; private String name; private int age;
我们可以使用@Autowired实现自动装配,它有很多种使用方式:
直接写在属性上是可以不要set方法的。
public class People { @Autowired private Dog dog; @Autowired private Cat cat; private String name; private int age;
public class People { private Dog dog; private Cat cat; private String name; private int age; @Autowired public void setDog(Dog dog) { this.dog = dog; }
当我们在开放中,需要在Spring容器中装配多个同一类型的对象时,可以使用@Autowried结合@Qualifer一起使用
public class People { @Autowired @Qualifier(value = "dog2") private Dog dog;
@Resource是jdk自带的注解,他比@Autowried更强大,但不咋用。
使用@Resource自动装配也是可以不用set方法的。
public class People { @Resource private Dog dog; @Resource(name = "cat2") private Cat cat; private String name; private int age;
都可以实现自动装配的功能;
Autowried是Spring框架的注解,Resource是JDK自带的注解;
Autowried默认采用的是byType的方式实现的自动装配,当存在多个同一类型的bean时,需要结合Qualifer实现自动装配;
Resource默认采用的是byName的方式实现的自动装配,当根据名称匹配不到bean的id时,会自动切换到byType进行匹配,当存在多个同一类型的bean时,可以根据Resource中设置的name的值进行匹配。
原文:https://www.cnblogs.com/chao666/p/12852881.html