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;
相关推荐
泡海椒1 分钟前
JQuick-Excel 项目定位与适用场景:声明式 Java Excel 的边界
java·开发语言·excel
AC赳赳老秦5 分钟前
财报附注表格精准提取:OpenClaw 从 PDF 年报附注挖掘隐藏明细,补齐财务分析维度
java·汇编·c++·python·青少年编程·deepseek·openclaw
箓维11 分钟前
线程的优缺点,与进程的关联和差异
java·服务器·笔记
曹牧12 分钟前
Spring MVC:@RequestMapping
java·spring·mvc
曹牧32 分钟前
Spring MVC : Controller 层URL划分
java·运维·服务器·前端
卓怡学长1 小时前
w203基于springboot钢材仓库管理系统的设计与实现
java·spring boot·spring·intellij-idea
sunburn-1 小时前
Java 排序算法详细教学:从冒泡排序到快速排序
java·开发语言·数据结构·ide·算法
我是小白呀1 小时前
编排还是事件协作?用 AcmeFlow 讲清企业 Workflow 的控制权
java·开发语言
深入云栈1 小时前
Netty 4.2.x 源码深度解析 (十四):KQueue 传输 —— macOS 高性能 IO 的 Netty 实现
java·后端
信誓旦旦的程序猿1 小时前
【Python 量化取数指南 #13】Python 把行情落库:sqlite 一键存,回测随用随取
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据api