spring java config 初探

本文介绍Spring框架中的JavaConfig配置方式,包括主要注解如@Configuration、@Bean和@ComponentScan的使用方法,通过示例展示了如何使用JavaConfig替代XML配置来定义Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Config 注解

spring java config作为同xml配置形式的另一种表达形式,使用的场景越来越多,在新版本的spring boot中
大量使用,今天我们来看下用到的主要注解有哪些。

  1. Configuration: 继承Component注解,默认解析为spring的顶级BeanFactory。作用于类上面,等价于applicationContext.xml文件
  2. Bean :作用在方法上面,方法的返回值为类实例。等同于
  3. ComponentScan:类级注解,用于配置扫描的包路径。等同于

接下来看一个实例

    //注释声明容器
    @Configuration
    public class HelloWorldConfig {
        //配置一个id=helloBean的bean,并返回对应的实例
        @Bean(name = "helloBean")
        public HelloWorld helloWorld() {
            return new HelloWorldImpl();
        }
    }

这个写法等同于

    <bean id ="helloBean" class="cn.lee.jason.hello.impl.HelloWorldImpl"></bean>

配置结束了,使用方面基本没有大的差异。
JavaConfig方式,使用AnnotationConfigApplicationContext类加载JavaConfig配置信息

    class TestHelloConfig{
        public static void main(String[] args) {
          ApplicationContext ctx = 
          new AnnotationConfigApplicationContext(HelloWorldConfig.class);
          
          HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
       
          helloWorld.setMessage("Hello World!");
          helloWorld.getMessage();
       } 
    }

如果需要注册加载多个BeanFactory的时候

class TestHelloConfig{
        public static void main(String[] args) {
          AnnotationConfigApplicationContext ctx = 
             new AnnotationConfigApplicationContext();
          
             ctx.register(AppConfig.class, OtherConfig.class);
             ctx.register(AdditionalConfig.class);
             ctx.refresh();
          
             MyService myService = ctx.getBean(MyService.class);
             myService.doStuff();
       } 
    }

在某种程度上面,java config简化了xml配置,但也导致修改场景丢失了一定的灵活性。面对快速搭建测试环境时比较方面快捷。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值