从Spring 3起,JavaConfig功能已经包含在Spring核心模块,它允许开发者将bean定义从在Spring配置XML文件转移到Java类中。
1.Bean
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
2.Dao
public interface HelloWorld {
void printHelloWorld(String msg);
}
3.Service
public class HelloWorldImpl implements HelloWorld {
@Override
public void printHelloWorld(String msg) {
System.out.println("Hello : " + msg);
}
}
4.执行结果
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHelloWorld("Spring Java Config");
}
}
5.@Import示例
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
}