2021-05-03 09:46  阅读(141)
文章分类:Spring 入门教程 文章标签:SpringSpring 教程
©  原文作者:一点教程 原文地址:http://www.yiidian.com/spring/

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)。

一、编写SpringConfig作为Spring环境启动类

    
    package com.yiidian.test;
    
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author http://www.yiidian.com
     *
     */
    @Configuration
    public class SpringConfig {
    	
    	public SpringConfig(){
    		System.out.println("Spring环境初始化成功!");
    	}
    	
    }
    

相当于:

    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
    
    
    </beans>

二、编写测试类

    
    package com.yiidian.test;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Demo1 {
    	@Test
    	public void test1(){
    		//@Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
    		ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    	}
    }
    

三、运行结果

2021050309460240110_1.png

源码下载:http://pan.baidu.com/s/1pLeGwX1

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 零配置-@Configuration
上一篇
@Resource装配实例
下一篇
零配置-@ComponentScan