Spring核心注解的应用
- Spring框架功能整体介绍
- Spring容器继承图
- Spring IOC 容器底层注解使用
Spring框架功能整体介绍
Spring Core Container
Core和Beans模块是框架的基础部分,提供IoC和依赖注入特性
ioc的思想最核心的地方在于,资源不由使用资源的双方管理,而由不使用资源的第三方管理,这可以带来很多好处。第 一,资源集中管理,实现资源的可配置和易管理。第二,降低了使用资源双方的依赖程度,也就是我们说的耦合度。
- Core主要包含Spring框架基本的核心工具类,Spring的其他组件都要用到这个包里的类。
- Beans包含访问配置文件,创建和管理bean以及进行(IoC/DI)操作相关的所有类
- Context模构建于 Core 和 Beans 模块基础之上,提供了一种类似JNDI 注册器的框 架式的对象访问方法。 Context 模块继承了 Beans 的特性,为 Spring 核 心提供了大量扩展,添加了对国际化(例如资源绑定)、事件传播、资源加载和对 Context 的透明创建的支持。 Context 模块同时 也支持 J2EE 的一些特性, ApplicationContext 接口是 Context 模块的关键
- Expression Language 模块提供了强大的表达式语言,用于在运行时查询和操纵对象。 它是 JSP 2.1 规范中定义的unifed expression language 的扩展。 该语言支持设值/获取属性的值,属性的分配,方法的调用,访问数组上下文( accessiong the context of arrays )、 容器和索引器、逻辑和算术运算符、命名变量以 及从Spring的 IoC 容器中根据名称检索对象。 它也支持list 投影、选择和一般的 list 聚合
Spring容器继承图
Spring IOC 容器底层注解使用
1.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.yemuxia.ioc02.Person">
<property name="id" value="1"/>
<property name="name" value="张三"/>
</bean>
</beans>
package com.yemuxia.ioc02;
public class Person {
private Integer id;
private String name;
public Person() {
System.out.println("我是构造函数");
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package com.yemuxia.ioc02;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("XmlBean.xml");
Person person = (Person)ctx.getBean("person");
System.out.println(person);
}
}
2.基于读取配置类的形式定义Bean信息
package com.yemuxia.ioc03;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
@Bean
public Person person1(){
return new Person();
}
}
package com.yemuxia.ioc03;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Arrays;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
String[] beanNames = context.getBeanDefinitionNames();
Arrays.stream(beanNames).forEach(System.out::println);
}
}
通过@Bean的形式是使用的话, bean的默认名称是方法名,若@Bean(value=“bean的名称”) 那么bean的名称是指定的
3.在配置类上写@CompentScan注解来进行包扫描
package com.yemuxia.ioc01;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("com.yemuxia.ioc01")
public class AppConfig {
}
package com.yemuxia.ioc01;
import org.springframework.stereotype.Controller;
@Controller
public class TestController {
}
package com.yemuxia.ioc01;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
String[] beanDefinationNames = context.getBeanDefinitionNames();
for (String name:beanDefinationNames) {
System.out.println("bean的定义信息:"+name);
}
}
}
排除用法 excludeFilters
package com.yemuxia.ioc01;
import org.springframework.stereotype.Service;
@Service
public class TestService {
}
package com.yemuxia.ioc01;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@ComponentScan(basePackages = "com.yemuxia.ioc01", excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {TestService.class})
})
public class AppConfig {
}
包含用法 includeFilters
注意,若使用包含的用法,需要把useDefaultFilters属性设置为false(true表示扫描全部的)
package com.yemuxia.ioc01;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@ComponentScan(basePackages = "com.yemuxia.ioc01", includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})
}, useDefaultFilters = false)
public class AppConfig {
}
@ComponentScan.Filter type的类型
FilterType.CUSTOM 自定义类型
package com.yemuxia.ioc01;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
public class TestFilterType implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//获取当前类的注解源信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//获取当前类的class的源信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//获取当前类的资源信息
Resource resource = metadataReader.getResource();
System.out.println("类的路径:"+classMetadata.getClassName());
if(classMetadata.getClassName().contains("Dao")) {
return true;
}
return false;
}
}
package com.yemuxia.ioc01;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
@ComponentScan(basePackages = "com.yemuxia.ioc01", excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,value = TestFilterType.class)
})
public class AppConfig {
}
4.配置Bean的作用域对象
在不指定@Scope的情况下,所有的bean都是单实例的bean,而且是饿汉加载(容器启动实例就创建好了)
package com.yemuxia.ioc03;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class TestConfig {
@Bean
@Scope(value = "prototype")
public Person person1(){
return new Person();
}
}
指定@Scope为 prototype 表示为多实例的,而且还是懒汉模式加载(IOC容器启动的时候,并不会创建对象,而是 在第一次使用的时候才会创建)
@Scope指定的作用域方法取值
- a) singleton 单实例的(默认)
- b) prototype 多实例的
- c) request 同一次请求
- d) session 同一个会话级别
package com.yemuxia.ioc03;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class TestConfig {
@Bean
@Lazy
public Person person1(){
return new Person();
}
}
Bean的懒加载@Lazy(主要针对单实例的bean 容器启动的时候,不创建对象,在第一次使用的时候才会创建该对象)
5.@Conditional进行条件判断
package com.yemuxia.ioc04;
public class TestComponentA {
public TestComponentA() {
System.out.println("组件A的构造方法");
}
}
package com.yemuxia.ioc04;
public class TestComponentB {
public TestComponentB() {
System.out.println("组件B的构造方法");
}
}
package com.yemuxia.ioc04;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
@Bean
public TestComponentA testComponentA(){
return new TestComponentA();
}
@Bean
@Conditional(value = TestCondition.class)
public TestComponentB testComponentB(){
return new TestComponentB();
}
}
package com.yemuxia.ioc04;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class TestCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判断容器中是否有testComponentA的组件
if(context.getBeanFactory().containsBean("testComponentA")) {
return true;
}
return false;
}
}
package com.yemuxia.ioc04;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
String[] beanNames = context.getBeanDefinitionNames();
Arrays.stream(beanNames).forEach(System.out::println);
}
}
package com.yemuxia.ioc04;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
//@Bean
public TestComponentA testComponentA(){
return new TestComponentA();
}
@Bean
@Conditional(value = TestCondition.class)
public TestComponentB testComponentB(){
return new TestComponentB();
}
}
容器中有TestComponentA的实例,那么TestComponentB才会被实例化
6.往IOC 容器中添加组件的方式
- 通过@CompentScan +@Controller @Service @Respository @compent 适用场景: 针对我们自己写的组件可以通过该方式来进行加载到容器中。
- 通过@Bean的方式来导入组件(适用于导入第三方组件的类)
- 通过@Import来导入组件 (导入组件的id为全类名路径)
- 通过实现FacotryBean接口来实现注册组件
通过@Import方式导入组件
package com.yemuxia.ioc5;
public class Car {
}
package com.yemuxia.ioc5;
public class Cat {
}
package com.yemuxia.ioc5;
public class Dog {
}
package com.yemuxia.ioc5;
public class Person {
}
package com.yemuxia.ioc5;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
public class TestBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Cat.class);
registry.registerBeanDefinition("cat",rootBeanDefinition);
}
}
package com.yemuxia.ioc5;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class TestImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.yemuxia.ioc5.Dog"};
}
}
package com.yemuxia.ioc5;
import org.springframework.context.annotation.Import;
@Import(value = {Person.class, Car.class, TestImportSelector.class, TestBeanDefinitionRegister.class})
public class TestConfig {
}
package com.yemuxia.ioc5;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
String[] beanNames = context.getBeanDefinitionNames();
Arrays.stream(beanNames).forEach(System.out::println);
}
}
通过实现FacotryBean接口来实现注册组件
package com.yemuxia.ioc6;
public class Car {
}
package com.yemuxia.ioc6;
import org.springframework.beans.factory.FactoryBean;
/**
* 通过实现FactoryBean接口往容器中注册组件
*/
public class CarFactoryBean implements FactoryBean<Car> {
@Override
public Car getObject() throws Exception {
return new Car();
}
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return false;
}
}
package com.yemuxia.ioc6;
import org.springframework.beans.factory.FactoryBean;
import java.sql.DriverManager;
public class DriverFactoryBean implements FactoryBean {
private String jdbcUrl;
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
@Override
public Object getObject() throws Exception {
return DriverManager.getDriver(jdbcUrl);
}
@Override
public Class<?> getObjectType() {
return java.sql.Driver.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
package com.yemuxia.ioc6;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(locations = {"classpath:beans.xml"})
public class AppConfig {
@Bean
public CarFactoryBean carFactoryBean(){
return new CarFactoryBean();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="car" class="com.yemuxia.ioc6.Car"/>
<bean id="driverFactoryBean" class="com.yemuxia.ioc6.DriverFactoryBean">
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/yemuxia"/>
</bean>
</beans>
package com.yemuxia.ioc6;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Object bean = ctx.getBean("carFactoryBean");
System.out.println(bean);
Object bean2 = ctx.getBean("&carFactoryBean");
System.out.println(bean2);
System.out.println(bean.getClass());
System.out.println(bean2.getClass());
Object bean3 = ctx.getBean("carFactoryBean");
System.out.println(bean==bean3);
CarFactoryBean carFactoryBean = ctx.getBean(CarFactoryBean.class);
System.out.println(carFactoryBean);
System.out.println(ctx.getBean("driverFactoryBean"));
}
}
7.Bean的初始化方法和销毁方法
什么是Bean的生命周期
bean的实例化——》属性赋值——》初始化——》销毁
由容器管理Bean的生命周期,我们可以通过自己指定bean的初始化方法和销毁方法。
- 针对单实例bean的话,容器启动的时候,bean的对象就创建了,而且容器销毁的时候,也会调用Bean的销毁方法
- 针对多实例bean的话,容器启动的时候,bean是不会被创建的而是在获取bean的时候被创建,而且bean的销毁不受 IOC容器的管理.
单实例bean演示
package com.yemuxia.ioc7;
public class Car {
public Car() {
System.out.println("Car的构造方法..........");
}
public void init() {
System.out.println("Car的初始化方法......init");
}
public void destroy() {
System.out.println("Car的销毁方法.....destroy");
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc7")
public class AppConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
ctx.close();
}
}
多实例bean
package com.yemuxia.ioc7;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc7")
public class AppConfig {
@Scope(value = "prototype")
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Car car = ctx.getBean(Car.class);
ctx.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(car);
}
}
通过 InitializingBean和DisposableBean 的二个接口实现bean的初始化以及销毁方法
package com.yemuxia.ioc7;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Person implements InitializingBean,DisposableBean {
public Person() {
System.out.println("Person的构造方法");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean的destroy()方法 ");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean的 afterPropertiesSet方法");
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc7")
public class AppConfig {
@Scope(value = "prototype")
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
@Bean
public Person person(){
return new Person();
}
}
通过JSR250规范 提供的注解@PostConstruct 和@ProDestory标注的方法
package com.yemuxia.ioc7;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Book {
public Book() {
System.out.println("book 的构造方法");
}
@PostConstruct
public void init() {
System.out.println("book 的PostConstruct标志的方法");
}
@PreDestroy
public void destory() {
System.out.println("book 的PreDestory标注的方法");
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc7")
public class AppConfig {
@Scope(value = "prototype")
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
@Bean
public Person person(){
return new Person();
}
@Bean
public Book book(){
return new Book();
}
}
通过Spring的BeanPostProcessor的 bean的后置处理器会拦截所有bean创建过程
- postProcessBeforeInitialization 在init方法之前调用
- postProcessAfterInitialization 在init方法之后调用
package com.yemuxia.ioc7;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class TestBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("TestBeanPostProcessor...postProcessBeforeInitialization:"+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("TestBeanPostProcessor...postProcessAfterInitialization:"+beanName);
return bean;
}
}
package com.yemuxia.ioc7;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc7")
public class AppConfig {
@Scope(value = "prototype")
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
@Bean
public Person person(){
return new Person();
}
@Bean
public Book book(){
return new Book();
}
@Bean
public TestBeanPostProcessor testBeanPostProcessor(){
return new TestBeanPostProcessor();
}
}
BeanPostProcessor的执行时机
populateBean(beanName, mbd, instanceWrapper)
initializeBean{
applyBeanPostProcessorsBeforeInitialization()
invokeInitMethods{
isInitializingBean.afterPropertiesSet
自定义的init方法
}
applyBeanPostProcessorsAfterInitialization()方法
}
8.通过@Value和@PropertySource来给组件赋值
package com.yemuxia.ioc8;
import org.springframework.beans.factory.annotation.Value;
public class Person {
@Value("司马")
private String firstName;
@Value("#{28-8}")
private Integer age;
@Value("${person.lastName}")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", age=" + age +
", lastName='" + lastName + '\'' +
'}';
}
}
person.lastName=老贼
package com.yemuxia.ioc8;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value = {"classpath:person.properties"})
public class AppConfig {
@Bean
public Person person() {
return new Person();
}
}
package com.yemuxia.ioc8;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Person person = ctx.getBean(Person.class);
System.out.println(person.toString());
}
}
9.自动装配
自动装配首先时按照类型进行装配,若在IOC容器中发现了多个相同类型的组件,那么就按照 属性名称来进行装配
按类型装配
package com.yemuxia.ioc9;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"com.yemuxia.ioc9"})
public class AppConfig {
@Bean
public TestDao testDao2() {
TestDao testDao = new TestDao();
testDao.setFlag(2);
return testDao;
}
}
package com.yemuxia.ioc9;
public class TestDao {
private int flag=1;
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
@Override
public String toString() {
return "TestDao{" +
"flag=" + flag +
'}';
}
}
package com.yemuxia.ioc9;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BaiDuService {
@Autowired
private TestDao testDao;
@Override
public String toString() {
return "BaiDuService{" + testDao +
'}';
}
}
package com.yemuxia.ioc9;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
//测试@AutoWired使用的时byName还是byType(默认是使用byType,当发现多个相同类型的bean话 就通过byName)
//需要指定装配的名称通过@Qualifier指定名称装配
BaiDuService baiDuService = ctx.getBean(BaiDuService.class);
System.out.println(baiDuService);
}
}
按属性装配(多个相同类型的bean)
package com.yemuxia.ioc9;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"com.yemuxia.ioc9"})
public class AppConfig {
@Bean
public TestDao testDao2() {
TestDao testDao = new TestDao();
testDao.setFlag(2);
return testDao;
}
@Bean
public TestDao testDao3() {
TestDao testDao = new TestDao();
testDao.setFlag(3);
return testDao;
}
}
该段代码报错,报错的原因就是因为Spring容器中存在多个相同类型的bean实例,进行自动装配时会按照实例名称进行装配。然而在容器中未找到匹配的实例名称(testDao)。因此报错。
假设我们容器中未找到匹配的实例名称,那么在装配的时候就会抛出异常 No qualifying bean of type ‘com.tuling.testautowired.TulingDao’ available 若我们想不抛异常 ,我们需要指定 required为false的时候可以了
使用@Qualifier(“testDao”)来指定装配的组件
package com.yemuxia.ioc9;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class BaiDuService {
@Autowired
@Qualifier(value = "testDao3")
private TestDao testDao;
@Override
public String toString() {
return "BaiDuService{" + testDao +
'}';
}
}
在配置类上的@Bean加上@Primary注解
package com.yemuxia.ioc9;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
@ComponentScan(basePackages = {"com.yemuxia.ioc9"})
public class AppConfig {
@Bean
public TestDao testDao2() {
TestDao testDao = new TestDao();
testDao.setFlag(2);
return testDao;
}
@Bean
@Primary
public TestDao testDao3() {
TestDao testDao = new TestDao();
testDao.setFlag(3);
return testDao;
}
}
@Autowired,@Resource,@Inject的区别:
- 1、@Autowired是spring自带的,@Inject是JSR330规范实现的,@Resource是JSR250规范实现的,需要导入不同的包
- 2、@Autowired、@Inject用法基本一样,不同的是@Autowired有一个request属性
- 3、@Autowired、@Inject是默认按照类型匹配的,@Resource是按照名称匹配的
- 4、@Autowired如果需要按照名称匹配需要和@Qualifier一起使用,@Inject和@Named一起使用
10.自己写的组件需要使用spring ioc的底层组件的时候,比如 ApplicationContext等
我们可以通过实现XXXAware接口来实现
package com.yemuxia.ioc10;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.yemuxia.ioc10")
public class AppConfig {
}
package com.yemuxia.ioc10;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class TestCompent implements ApplicationContextAware,BeanNameAware {
private ApplicationContext applicationContext;
@Override
public void setBeanName(String name) {
System.out.println("current bean name is :【"+name+"】");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
package com.yemuxia.ioc10;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
}
}
11.通过@Profile注解 来根据环境来激活标识不同的Bean
@Profile标识在类上,那么只有当前环境匹配,整个配置类才会生效 @Profile标识在Bean上 ,那么只有当前环境的Bean才会被激活
没有标志为@Profile的bean 不管在什么环境都可以被激活
package com.yemuxia.ioc11;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;
import javax.sql.DataSource;
@Configuration
@PropertySource(value = {"classpath:ds.properties"})
public class AppConfig implements EmbeddedValueResolverAware {
@Value("${ds.username}")
private String userName;
@Value("${ds.password}")
private String password;
private String jdbcUrl;
private String classDriver;
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
}
@Bean
@Profile(value = "test")
public DataSource testDs() {
return buliderDataSource(new DruidDataSource());
}
@Bean
@Profile(value = "dev")
public DataSource devDs() {
return buliderDataSource(new DruidDataSource());
}
@Bean
@Profile(value = "prod")
public DataSource prodDs() {
return buliderDataSource(new DruidDataSource());
}
private DataSource buliderDataSource(DruidDataSource dataSource) {
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setDriverClassName(classDriver);
dataSource.setUrl(jdbcUrl);
return dataSource;
}
}
ds.username=root
ds.password=123456
ds.jdbcUrl=jdbc:mysql://localhost:3306/skq
ds.classDriver=com.mysql.jdbc.Driver
package com.yemuxia.ioc11;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("test","dev");
ctx.register(AppConfig.class);
ctx.refresh();
printBeanName(ctx);
}
private static void printBeanName(AnnotationConfigApplicationContext ctx){
for(String beanName:ctx.getBeanDefinitionNames()) {
System.out.println("容器中的BeanName:"+beanName);
}
}
}
激活切换环境的方法
- 方法一:通过运行时jvm参数来切换
-Dspring.profiles.active=test|dev|prod - 方法二:通过代码的方式来激活