- 自动装配是Spring满足Bean以来的一种方式
- Spring会在上下文自动寻找,并自动给bean装配属性
在Spring中有三种装配方式
- 在xml中显示的配置
- 在Java中的显示配置
- 隐式的自动装配bean【重点】
1、自动装配(xml显示配置)
<bean name="dog" class="com.xian.pojo.Dog"></bean> <bean name="cat" class="com.xian.pojo.Cat"></bean> <bean name="person" class="com.xian.pojo.Person" autowire="byName"> <property name="name" value="people"/> </bean>
Byname:会自动在容器上下文找,和自己set方法后面对应的beanid
ByType:会自动在容器上下文找,和自己对象属性对应的bean
<bean name="dog" class="com.xian.pojo.Dog"></bean> <bean name="cat" class="com.xian.pojo.Cat"></bean> <bean name="person" class="com.xian.pojo.Person" autowire="byType"> <property name="name" value="people"/> </bean>
2、使用注解完成自动装配(隐形配置)
注意添加功能 <context:annotation-config/>
beans.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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean name="dog22" class="com.xian.pojo.Dog"></bean> <bean name="cat" class="com.xian.pojo.Cat"></bean> <bean name="person" class="com.xian.pojo.Person"> <property name="name" value="hanhan"/> </bean> </beans>
@Autowired(@Nullable =false 允许字段为null)
@Qualifier(value="dog22") 指定bean
public class Person { @Autowired private Cat cat; @Autowired private Dog dog; private String name;}
可以在属性上使用,也可以在set方法上使用
@Resource注解
public class Person { @Resource private Cat cat; @Resource private Dog dog; private String name; }
@Autowired、@Resource注解的区别
- 都是用来自动装配的,都可以放在属性字段身上
-
@Autowired是通过ByType的方式实现的,而且必须要求这个对象存在
-
@Resource默认通过ByName的方式实现的,如果找不到名字,则通过ByType的方式
- 执行循序不同,
3、Config配置文件【重点】(Java显示配置)
配置文件加入@Configuration,对应的Bean加入@Bean
@Configuration //这个也会被Spring容器托管,注册到容器中因为它本省就是一个@Component //@Configration本身就是一个配置类,和Beans.xml是一样的 @ComponentScan("com.xian.dao") public class Config { //注册一个Bean就相当于之前的一个Bean标签 //这个方法的名字就是Bean标签中的ID属性 //方法的返回值就相当于bean标签当中的class属性 @Bean public User getuser(){ return new User(); } }
普通类
类中只进行值得注入@Component(打开服务)@Value("hanhanhan")
@Component public class User { // @Value等价于<property name="name" value="hanh"/> public String name; public String getName() { return name; } @Value("hanhanhan") public void setName(String name) { this.name = name; } }
Test
public void TestConfig(){ ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); User getuser = context.getBean("getuser",User.class); System.out.println(getuser.getName()); }