Spring中重要三张图(个人意见)
BeanFactory: Spring规定所有IOC容器必须继承BeanFactory。(IOC超类)
Aware: 非常重要,控制Bean生命周期的接口许多是Aware的子接口。
Spring Bean: 生命周期图
思路流程:
- IOC之加载
- IOC之注入
- Bean的生命周期
- properties文件
- profile
- SpringEL:@Value的使用
1. IOC加载
a. @Component : 作用在要装载的Bean上,用于容器扫描标识
b. @ComponentScan : 常用在启动类上。
basePackages:标识扫描包路径(包括子包)下所有类,
excludeFilters={@Filter(classes={A.class,B.class})} :扫描排除
includeFilters={@Filter(classes={C.class,D.class})} : 扫描包含
c. @Condition : 作用在要装载的Bean上,用于条件装载。
eg:
@Bean(name="simpleBean")
@Condition(SimpleCondition.class)
pubilc class SimpleBean{}
//必须实现Condition接口
public SimpleCondition implements Condition{
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
Environment env = context.getEnvironment(); //获取配置文件
returen env.containsProperty("simplebean.make");//检测是否配置simplebean.make
}
}
d. @ImportResource : 注入xml文件
eg: @ImportResource(value={"classpath:test.xml"})
e. @PropertySource : 注入properties文件
eg: @PropertySource(value={"classpath:test.properties"},ignoreResourceNotFound=true)
2. 依赖注入DI:
a. @Autowired : 使用by type注入,如果by type下多个使用属性变量名by name注入。
eg:
@Autowired
private A aChild1;
//如果A类是父类,且本身没有@Component装载,但多个子类已经装载,装载子类BeanName=aChild1的子类,如果装载过程中没有找到目标,则抛出异常。
b. @Qualifier :与@autowired搭配使用,利用type和name准确装载
eg:
@Autowired
@Qualifier("aClild1")
private A a;
c. @Primary : 优先级装载标识。如果多个子类装载,注入的时候优先注入子类上有@Primary标识的。
3. bean的生命周期:一个类来描述
eg:
@Component
public class beanLife implements BeanNameAware,BeanFactoryAware,ApplicationContextAware,InitializingBean,DisposableBean{
@Override
public xxx xxx(){}
...
@PostConstruct
public void init(){
//自定义初始化
}
@PreDestory
public void destory(){
//自定义摧毁
}
}
//可以查看:https://www.cnblogs.com/sishang/p/6576665.html
@Component
public class SimpleBeanPostProcessor implements BeanPostProcessor{
@Overvide
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Overvide
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
4. properties文件
a. @PropertySource(value={"classpath:test.properties"}): 指定引入配置文件
b. @ConfigurationProperties(prefix="redis"): 将properties文件中配置的前缀是redis的键值赋值给当前bean中。
5. profile
a. @Profile("dev")
b. spring.profiles.active : 可以在配置文件中指定,也可以在运行参数中指定。
eg:
application.properties文件中
spring.profiles.active=dev
命令行
java -jar xx.jar --spring.profiles.active=dev
6. SpringEL: @Value的使用,将配置文件中value赋值给bean中属性
@Value(${server.port})
private String port;
@Value(#{23})
private int day;
@Value(#(T(System).currentTimeMillis()))
private Long currentTime = null;
// T(...): 引入类
// System: java.lang.*包下,不用写全路径,不是lang包下要写全路径
// .currentTimeMillis(): System的静态方法
干货不谢:( *-* )
https://mp.weixin.qq.com/s/nSIyS35N6KpnFCWdI43THA