Reference: http://wiki.jikexueyuan.com/project/spring/java-based-configuration.html
@Configuration and @Bean annotations
Annotated classes with @Configuration indicate that the class can use the Spring IoC container as the source for the bean definition. @Bean Note tells Spring that an annotation method with @Bean will return an object that should be registered as a Bean in the context of the Spring application. The simplest possible @Configuration classes are as follows:
1 Packageorg.wzh.di.demo1.congiration;2 3 ImportOrg.springframework.context.annotation.Bean;4 Importorg.springframework.context.annotation.Configuration;5 6 @Configuration7 Public classHelloworldconfig {8 @Bean9 PublicHelloWorld HelloWorld () {Ten return NewHelloWorld (); One } A}
1 Packageorg.wzh.di.demo1.congiration;2 3 Public classHelloWorld {4 5 PrivateString message;6 7 PublicString getMessage () {8 returnmessage;9 }Ten One Public voidsetmessage (String message) { A This. Message =message; - } - the}
1 Packageorg.wzh.di.demo1.congiration;2 3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext;5 6 Public classTest {7 8 Public Static voidMain (string[] args) {9ApplicationContext CTX =NewAnnotationconfigapplicationcontext (Helloworldconfig.class);TenHelloWorld HelloWorld = Ctx.getbean (HelloWorld.class); OneHelloworld.setmessage ("Hello world!"); AString msg =helloworld.getmessage (); - System.out.println (msg); - } the -}
You can also load other configuration classes, where only write usage
1 Packageorg.wzh.di.demo1.congiration;2 3 ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext;4 5 Public classTest2 {6 7 Public Static voidMain (string[] args) {8Annotationconfigapplicationcontext CTX =NewAnnotationconfigapplicationcontext ();9Ctx.register (Helloworldconfig.class);Ten Ctx.refresh (); OneHelloWorld HelloWorld = Ctx.getbean (HelloWorld.class); AHelloworld.setmessage ("Hello World 2!")); -String msg =helloworld.getmessage (); - System.out.println (msg); the } - -}
[email protected] and @Bean