从Spring 3起,JavaConfig功能已经包含在Spring核心模块,它允许开发者将bean定义和在Spring配置XML文件到Java类中。
需要先加载spring-context 包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency>
代码:
package com.company; /** * Created by Administrator on 2017/2/22 0022. */ public interface ISay { void say(String msg); }
package com.company; /** * Created by Administrator on 2017/2/22 0022. */ public class SayImpl implements com.company.ISay { public void say(String msg){ System.out.println("Person Say:"+msg); } }
使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,并通过 @Bean 定义 bean。
package com.company; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by Administrator on 2017/2/22 0022. */ @Configuration public class JavaConfig { @Bean(name="GetSay") public com.company.ISay GetSay(){ return new com.company.SayImpl(); } }
package com.company; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context =new AnnotationConfigApplicationContext(com.company.JavaConfig.class); com.company.ISay obj=(com.company.ISay) context.getBean("GetSay"); obj.say("hongdada"); } }
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Person Say:hongdada
多个Bean
package com.company; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; interface ISay { String Country="China"; void say(String msg); } class SayImpl implements com.company.ISay { public void say(String msg){ System.out.println("Person Say:"+msg); } } class SayImpl2 implements com.company.ISay { public void say(String msg){ System.out.println(com.company.ISay.Country+" Person2 Say:"+msg); } } @Configuration class JavaConfig { @Bean(name="GetSay") public com.company.ISay GetSay(){ return new com.company.SayImpl(); } @Bean(name="GetSay2") public com.company.ISay GetSayTwo(){ return new com.company.SayImpl2(); } } public class Main { public static void main(String[] args) { ApplicationContext context =new AnnotationConfigApplicationContext(com.company.JavaConfig.class); com.company.ISay obj=(com.company.ISay) context.getBean("GetSay"); obj.say("hongdada"); com.company.ISay obj2=(com.company.ISay) context.getBean("GetSay2"); obj2.say("hongdada"); } }