@Configuration+@Bean,@Import,@Conditional 实现原理以及应用场景
LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。
目录
概述
@Configuration+@Bean,@Import,@Conditional 实现原理以及应用场景
实现思路分析
Configuration
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器
@Configuration不可以是final类型; @Configuration不可以是匿名类;嵌套的configuration必须是静态类。
用@Configuration加载Spring
@Configuration配置spring并启动spring容器
@Configuration启动容器+@Bean注册Bean
@Configuration启动容器+@Component注册Bean
使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)
@Component,@Bean
@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
@Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑.
两者的目的是一样的,都是注册bean到Spring容器中。
@Component(@Controller、@Service、@Repository)通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。
而@Bean注解通常是我们在标有该注解的方法中定义产生这个bean的逻辑。
@Import注解
@Import是Spring基于 Java 注解配置的主要组成部分。@Import注解提供了@Bean注解的功能,同时还有原来Spring基于 xml 配置文件里的标签组织多个分散的xml文件的功能,当然在这里是组织多个分散的@Configuration的类。
在4.2之前只支持导入配置类
在4.2,@Import注解支持导入普通的java类,并将其声明成一个bean.
举例:
package com.example.demo.importtest;
public class DemoService {
public void doSomething(){
System.out.println("123--ok");
}
}
demo2:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(DemoService.class)
public class DemoConfig {
}
demo3:
package com.example.demo.importtest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ImportMainTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.example.demo.importtest");
DemoService ds = new DemoService();
ds.doSomething();
}
}
运行结果:
@Condition:
@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean
@Conditional的定义:
//此注解可以标注在类和方法上
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class<? extends Condition>[] value();
}
从代码中可以看到,需要传入一个Class数组,并且需要继承Condition接口:
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
Condition是个接口,需要实现matches方法,返回true则注入bean,false则不注入。
相关工具如下:
分析:
小结:
主要讲述了一些Spring IOC的设计理念相关集成,里面有许多不足,请大家指正~