spring-ioc

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;
相关推荐
EatFan5 小时前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端
辰海Coding5 小时前
平台如何接入一台物联网设备?又该如何设计它的通信协议?
java·物联网
代码民工正电荷6 小时前
JAVA重要知识点和集合
java·开发语言
李少兄7 小时前
IDEA Apifox Helper 插件踩坑:2.0.15-243 版本“导出指定接口”参数描述丢失问题解析与修复方案
java·ide·intellij-idea
努力攀登的小k7 小时前
《新手练表:从建表到删表全操作|从零学会表操作》
java·数据库·mysql
Yetian_20008 小时前
Postman测试上传图片文件接口
java·postman
爪哇碎碎念9 小时前
【Java】从一次 cache.get(key) 进去:缓存击穿一瞬间打出 200 次 DB,JDK 17 实测三种解法
java·redis·缓存
csdn_aspnet9 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
源码_空间9 小时前
基于Springboot的在线编程练习判题平台(源码+文档)
java·spring boot·后端
小手cool10 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法