Spring基于注解配置的容器

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介: Spring 容器的元数据可以基于注解配置,它比 XML 配置更简洁,而且提供了更多的上下文配置。两种配置方式各有优缺点,XML 配置不会侵入源代码,配置修改后不需要重新编译源文件。你可以在项目中任意选择哪种配置方式,或者两者混合使用。


一、Bean 管理



Spring 通过扫描指定包路径下所有的类(包括子包下的类),来寻找哪些类是要容器管理的。

默认情况下,根据类是否存在 @Component 注解(或其组合注解)来判断是否由容器管理。


1. 扫描类路径配置


基于 XML 配置

在 XML 配置文件中使用 context:component-scan 来配置扫描的包路径。

<beans>
    <context:component-scan base-package="cn.codeartist.spring.bean.annotation"/>
</beans>

使用 ClassPathXmlApplicationContext 来实例化容器。

public static void main(String[] args) {
    ApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("bean-annotation.xml");
    BeanExample beanExample = (BeanExample) applicationContext.getBean("beanExample");
}


基于注解配置

定义类并使用 @Configuration@ComponentScan 来配置扫描的包路径。

@Configuration
@ComponentScan(basePackages = "cn.codeartist.spring.bean.annotation")
public class AppConfig {
}

@ComponentScan 可以不指定 basePackages,默认扫描类(AppConfig)所在的包路径。

使用 AnnotationConfigApplicationContext 来实例化容器。

public static void main(String[] args) {
    ApplicationContext applicationContext =
        new AnnotationConfigApplicationContext(AppConfig.class);
    BeanExample beanExample = (BeanExample) applicationContext.getBean("beanExample");
}


2. 使用注解管理 Bean


在扫描的包下面,在类上面使用 @Component 注解来注册 Bean。

@Component
public class BeanExample {
    private String name;
    private Integer year;
    // Getter and setter
}

为了更明确 Bean 的业务用途,体现项目的分层结构,Spring 还提供了 @Service@Repository@Controller 等注解。

这些注解默认使用类名小驼峰格式作为 Bean 名称,也可以通过注解的 value 属性来指定。

BeanExample -> beanExample

Bean 作用域

使用 @Scope 注解来指定 Bean 的作用域。

@Component
@Scope("singleton")
public class BeanExample {
    private String name;
    private Integer year;
}

在基于 XML 配置容器中,使用 context:annotation-config 来配置注解注入。

<beans>
    <context:annotation-config/>
</beans>


如果 XML 配置文件中存在 context:component-scan,则不需要配置 context:annotation-config

Spring 通常使用 @Autowired@Resource 注解注入 Bean 依赖,@Autowired 注解默认通过类型注入。

@Resource 注解默认通过名称注入,只有匹配不到对应名称的 Bean,才会按类型注入。


1. 依赖注入


1.1 字段注入


直接在字段上面使用注解注入依赖。

@Component
public class BeanExample {
    private String name;
    private Integer year;
    @Autowired
    private BeanProvider beanProvider;
}


1.2 构造器注入


在构造器方法上使用注解注入依赖。

@Component
public class BeanExample {
    private String name;
    private Integer year;
    private BeanProvider beanProvider;
    @Autowired
    public BeanExample(BeanProvider beanProvider) {
        this.beanProvider = beanProvider;
    }
}


1.3 Setter 方法注入


在 Setter 方法上使用注解注入依赖。

@Component
public class BeanExample {
    private String name;
    private Integer year;
    private BeanProvider beanProvider;
    @Autowired
    public void setBeanProvider(BeanProvider beanProvider) {
        this.beanProvider = beanProvider;
    }
}


2. 依赖关系


使用 @DependsOn 注解指定依赖关系。

@Component
@DependsOn("beanProvider")
public class BeanExample {
    private String name;
    private Integer year;
    private BeanProvider beanProvider;
    // Getter and setter
}


3. 懒加载


使用 @Lazy 注解配置懒加载。

@Lazy
@Component
public class BeanProvider {
    // Fields
    // Getter and setter
}

懒加载 Bean 在注入的地方也要加上 @Lazy 注解,或者使用 ApplicationContext.getBean() 方法获取 Bean,才能使懒加载生效。

@Component
public class BeanExample {
    private String name;
    private Integer year;
    @Lazy
    @Autowired
    private BeanProvider beanProvider;
}


二、附录



1. 配置属性


属性 描述
context:component-scan 在基于 XML 配置容器中,指定扫描包路径
context:annotation-config 在基于 XML 配置容器中,启用注解注入依赖


2. 常用注解


注解 描述
@Configuration 指定 Bean 的配置类
@ComponentScan (默认为类所在的包)指定包路径,该包下的类由容器管理
@Component 指定该类由 Spring 容器管理
@Service @Component 一致,通常在业务层使用
@Repository @Component 一致,通常在数据层使用
@Controller @Component 一致,通常在控制层使用
@Autowired 配置自动注入,优先通过类型注入
@Resource 配置自动注入,优先通过名称注入
@Scope 指定 Bean 的作用域
@DependsOn 指定 Bean 的依赖关系
@Lazy 配置懒加载


3. 示例代码


Gitee 仓库:

https://gitee.com/code_artist/spring

项目模块:

spring-ioc

示例路径:

cn.codeartist.spring.bean.annotation


目录
相关文章
|
8天前
|
XML 前端开发 Java
一文搞懂 Spring Boot 自动配置原理
Spring Boot 自动配置原理揭秘:通过 `@EnableAutoConfiguration` 加载 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` 中的配置类,结合 `@Conditional` 按条件注入 Bean,实现“开箱即用”。核心在于约定大于配置,简化开发。
185 0
|
1月前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
1月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
417 128
|
1月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
12天前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
12天前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
20天前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
191 2
|
1月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
213 12
|
1月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
367 4
|
1月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
127 0
探索Spring Boot的@Conditional注解的上下文配置