美文网首页
Spring配置方式

Spring配置方式

作者: YoungJadeStone | 来源:发表于2020-05-14 00:39 被阅读0次

    Spring有三种配置方式:

    1. XML配置
    2. 注解配置(annotation)
    3. Java配置

    XML配置

    最经典

    注解配置

    Spring 2.0开始引入。
    @Service @Component @Repository @Controller
    比如

    @Component("userDao")
    public class userDao{......}
    

    等效于

    <bean id="userDao" class="cn.lovepi.***.userDao"/>
    

    Java配置

    基于Java类定义Bean配置元数据,其实就是通过Java类定义Spring配置元数据,且直接消除XML配置文件。
    具体步骤如下:

    • 用@Configuration标记一个类,表示该类将定义Bean的元数据
    • 用@Bean标记相应的方法,该方法名默认就是Bean的名称,该方法返回值就是Bean的对象。
    • AnnotationConfigApplicationContext或子类进行加载基于Java类的配置
      举例子:
    pkg com.mytest;
    
    @Configuration
    public class HelloWorldConfig {
        @Bean
        public HelloWorld message() {
            return new HelloWorld();
        }
    }
    

    上面的例子等效于:

    <beans>
      <bean id="helloWorld" class="com.mytest.HelloWorld" />
    </beans>
    

    定义好之后,我们可以通过AnnotationConfigApplicationContext加载到Spring container里面,来测试一下:

    public class ConfigurationTest {
        public static void main(String[] args) {
            ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
    
            HelloWorld hw = ctx.getBean(HelloWorld.class);
            hw.setMessage("hello");
            hw.getMessage();
        }
    }
    

    类似的,我们可以加载多个bean:

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

    reference:

    相关文章

      网友评论

          本文标题:Spring配置方式

          本文链接:https://www.haomeiwen.com/subject/qpnanhtx.html