spring-ioc
Bean是什么?
- Spring容器管理的对象实例
- 由Spring IoC容器负责创建、装配和管理
配置bean
- @Configuration + @Bean 配置bean
java
@Configuration // 声明这是一个Spring配置类
public class DogConfig {
@Bean // 声明这是一个Spring Bean的工厂方法
public Dog dog1(){
return new Dog(); // 使用无参构造函数创建Dog实例
}
@Bean // 声明另一个Bean
public Dog dog2(){
return new Dog("xm", 12); // 使用带参数的构造函数创建Dog实例
}
}
成为spring的bean后就可以被@Autowired注入
@Autowired
Map<String, Dog> dogMap;
@Autowired
Dog dog1;
- @Component | @Controller | @Service | @Repository也可以标注一个bean
注入Bean
@Autowired
-
注入规则 按照类型获取单个组件bean的规则[先按照类型,再按照名称]
只找到1个这样的类型,则直接注入,注入的变量名随便
如果找到多个类,再按照名称去找,变量名就是名字,如果找到则注入;如果没找到就报错
用构造器注入
java
@Slf4j
@Component
@Data
public class UserDao {
private final IPerson teacherImpl; // final表示必需!
// @Autowired
// private IPerson teacherImpl;
public UserDao(IPerson teacherImpl){
log.info("UserDao constructor:{}", teacherImpl);
this.teacherImpl = teacherImpl;
}
public void callPersonSay(){
teacherImpl.say("你好ya");
}
}
用构造器注入 对比 @Autowired注入,spring更推荐 用构造器注入
@Autowired注入隐藏依赖关系,代码不可靠。偷偷注入,外部看不出来; 但是用构造器注入一眼就知道需要哪些依赖@Autowired方式注入难以单元测试
Bean创建过程
容器启动过程中就会创建组件对象,故默认情况下组件是单例的,每次获取直接从spring容器中获取组件对象。
应用启动 → Bean扫描 → Bean定义注册 → 创建Bean实例 → 依赖解析 → 属性注入 → 初始化 → 使用
@ComponentScan
@ComponentScan是Spring框架中一个核心的注解,用于控制Spring容器扫描和注册Bean的范围
默认扫描规则
默认会扫描当前启动类所在包及其所有子包 下的组件@Component, @Service, @Repository, @Controller, @Configuration等。
当需要扫描非以上情况的包时,需要在启动类上使用@ComponentScan
java
@SpringBootApplication
@ComponentScan({
"com.mycompany.app",
"com.mycompany.common", // 扫描公共模块
"com.mycompany.security", // 扫描安全模块
"com.mycompany.service" // 扫描服务模块
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Value 给Spring Bean属性赋配置值
@Value 注解用于从各种来源配置值注入到Spring Bean的属性中。
java
// 没有PropertySource即默认取`resources`目录下的application.properties文件
// userDao.properties文件创建于`resources`目录下
@Component
@Data
@PropertySource("classpath:userDao.properties")
public class UserDao {
// 当不存在 key:user.dao.female 时,female的默认值为 1
@Value("${user.dao.female: 1}")
private String female;
}
@Profile 指定bean配置生效的环境
- 指定当前激活的环境
ini
// application.properties 文件中设置
spring.profiles.active=sit
- 各个环境的bean配置
java
// @Profile作用于 类 的时候,表面该类里所有的bean生效于当前环境
// @Profile作用于 bean方法 的时候,表面当前bean生效于当前环境
@Profile("dev")
@Configuration
public class DevConfig {
@Bean
public MyDataSource dev(){
return new MyDataSource("dev", "dev-wmy", "admin");
}
}
@Profile("sit")
@Configuration
public class SitConfig {
@Bean
public MyDataSource sit(){
return new MyDataSource("sit", "sit-wmy", "admin");
}
}
// 取的是当前环境生效的bean,若spring.profiles.active=sit,则当前myDataSource取的是sit的bean配置 new MyDataSource("sit", "sit-wmy", "admin");
@Autowired
MyDataSource myDataSource;