注解驱动
组件注册(注册bean)
@Configuration&@Bean给容器中注册组件
@ComponentScan-自动扫描组件&指定扫描规则
@ComponentScans
@Import-给容器中导入一个组件(benaName默认是全类名)
使用FactoryBean注册组件(注册得到工厂Bean还要配合@Bean注解使用)
bean的一些设置。(作用域、加载时机、注册条件)
@Scope-设置组件作用域
@Lazy-bean懒加载
@Conditional-按照条件注册bean(自定义condition)
生命周期
初始化(设置Bean属性后)和销毁
场景1、在配置数据源时
初始化时做一些属性赋值,建立连接池
销毁时,关闭连接
- @Bean注解可以指定initMethod(初始化在构造方法之后)和destroyMethod(销毁)(单实例bean)
- 或者bean类实现
DisposableBean接口(在BeanFactory销毁时)
InitializingBean接口(在Bean完成属性赋值之后) - jdk注解(在spring中能用是因为initDesBeanPostProcessor)
@PostConstruct(jsr250)(在Bean完成属性赋值之后)
@PreDestroy
场景2、在项目中数据源配置在Bean初始化时封装好了并且不想修改源码,如何扩展
- BeanPostProcessor在所有Bean初始化前后(注意这个是全局的)
方法postProcessBeforeInitialization在初始化方法前(InitializingBean、init-method之前)
postProcessAfterInitialization在初始化方法方法后
spring中的应用
bean赋值(xxxAware),注入其他组件,@Autowired,@Async
Bean属性赋值
@Value
创建配置文件
src/main/resources/application.yml
myuser:
name: 张三
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
//绑定配置文件
@PropertySource(value = "classpath:/application.yml")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserTest {
//从配置文件中获取值
@Value("${myuser.name}")
String name;
//使用表达式
@Value("#{20-2}")
Integer age;
//直接赋值
@Value("小三")
String nickName;
}