构造注入优先级比set注入高,所以同时存在时并且对同一个属性注入时,
最后的值会是set注入的值,因为构造注入的值会被set注入的值覆盖,
不是同时注入同一个属性时,则set注入的属性为set注入的值,
其他属性为构造注入的值或null(构造也没注入)
可看bean3.xml
从而抽取公共list类型注入
一种是普通bean,另一种是工厂bean(FactoryBean)
可看bean4.xml
1、普通bean,在配置文件定义的bean的类型就是返回的类型
2、工厂bean, 在配置文件中定义bean的类型可以和返回类型不一样
2.1 创建类,让这个类作为工厂bean,实现接口FactoryBean
2.2 实现接口里面的方法,并且在实现的方法中定义返回的bean类型
1 、在spring里面,创建的bean,默认是单实例
2、 在spring里面,如何设置单实例,以及如果设置多实例
scope属性值
singleton: 默认值,表示是单实例对象
设置scope值是singleton的时候,加载spring配置文件的时候就会创建单例对象
prototype: 表示是多实例对象
设置scope值是sprototype的时候,不是加载spring配置文件的时候创建对象,在调用getBean方法的时候创建多实例对象
创建类,实现接口BeanPostProcessor,创建后置处理器
重写接口的两个方法postProcessBeforeInitialization、postProcessAfterInitialization
可看bean5.xml
会为当前配置中(也就是bean5.xml)的所有bean都添加上后置处理器
可看bean6.xml
以上方式均为手动注入,自动注入有两种
1、autowire=“byName” 通过id名称自动注入,id是唯一的,此时可以找到唯一属性
2、autowire=“byType” 同一类型,可以多次注入,当一个对象多次注入时,则会报错,
expected single matching bean but found 2: emp,emp1
首先引入命名空间 context
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”>
1.1 引入aop的依赖
1.2 在xml里面开启组件扫描
1.3 新建类并且注入
@Service(value = “testService”)
value值可以不写,当不写的时候默认为类名首字母小写
@Controller、@Service、@Repository、@Component、四个的涵义作用是一样的,只是用在不同业务上
use-default-filters=“false” 表示不使用默认的fiter
1、设置扫描哪些内容: context:include-filter
2、设置不扫描哪些内容: context:exclude-filterr
1、@Autowire 根据属性类型进行自动装配
2、@Qualifier 根据属性名称自动装配
@Qualifier要和@Autowire一起使用,当多个实现类的时候,类型是一样的,此时需要用@Qualifier来区分名称。
@Autowire
@Qualifier(value=“testService”)
3、@Resource 可以根据类型注入,也可以根据名称注入
@Resource(name=“testService”)。是java的扩展包,不是Spring包里面的注解
4、@Value 注入普通类型属性
@Value(value=“abc”) 给属性赋值.
private String name;
@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.example.demo.entity.annotation","com.example.demo.entity.bean6"})
public class SpringConfig {
}
3.2 编写测试类
public class AnnotationTest {
//传统的xml方式测试
@Test
void testXml() {
ApplicationContext context = new ClassPathXmlApplicationContext("annotationConfig/bean1.xml");
TestService service = context.getBean("testService", TestService.class);
System.out.println(service);
service.test();
}
//使用注解方式测试
@Test
void testConfig() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
TestService service = context.getBean("testService", TestService.class);
System.out.println(service);
service.test();
}
}



