Spring中IOC自动装配
前言:
IOC的自动装配有三种装配方式:
1、根据自己的类型进行自动装配,他的将类型匹配的Bean作为一个注入,然后进行注入的。
2、根据名称(id)进行注入,他的方式就是必须将目标的Bena的名称和定义的ID属性的名字一样,否则会报错。
3、通过构造器自动装配,当Bean中存在多个构造器时的时候使用他。
什么是自动装配?
答:他和手动装配不同,手动装配是可以进行value和ref进行配置,因为他已经明确了指定的属性值,这个称之为手动装配,自动装配的是根据他的指定装配规则,不需要明确指定,spring自动装配将匹配的属性值注入到bean中
正文
1.创建所需的Bean
1.1.Cat的Bean
public void automatic(){
System.out.println("我是Cat");
}
1.2.Dog的Bean
public void automatic(){
System.out.println("我是Dog");
}
1.3.Auto的Bean,名字Auto可能不规范,但是仅是练习...
public class Auto {
/**
* 自动装配有Autowired和Resource
* Autowired 他是根据类型的type进行匹配如果没有查找name如果2个都没有的话就匹配不到了。
* Resource 他是根据name先进行匹配,如果没有的话在去type进行匹配,2中都没有的话就GG
* equired 他是可以进行为NULL的,作为理解就可以了。
* Autowired(required = false)他是可以定义为false 但是好像实际中用处不大,理解就好
* */
//开启自动装配
@Autowired
private Dog dog;
//开启自动装配
@Autowired
private Cat cat;
private Auto name;
//创建get、set、tostring
}
2.Spring中的IOC的注入一定要开启自动注解
并且配置context的自动注解,一下是案例
<?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/>
-->
<context:annotation-config/>
<!-- 配置名字和class的路径 -->
<bean id="dog" class="com.zzy.pojo.Dog" />
<bean id="cat" class="com.zzy.pojo.Cat"/>
<bean id="name" class="com.zzy.pojo.Auto"/>
</beans>
3.创建Test类
//记得导入junit Maven
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beansauto.xml");
Auto auto = (Auto) context.getBean("name");
//此处调用的Dog的方法
auto.getDog().automatic();
}

浙公网安备 33010602011771号