使用@Configuration注解类表明该类可以被Spring IoC容器用作bean定义的源。 @Bean注解(你问到的)告诉Spring,用@Bean注解的方法将返回一个应该在Spring应用程序上下文中注册为bean的对象。最简单的可能@Configuration类将是如下 -
package com.test;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
将上面的代码等同于以下XML配置 -
<beans>
<bean id = "helloWorld" class = "com.test.HelloWorld" />
</beans>
这里,方法的名称标注有@Bean工作豆ID并创建并返回实际的bean。您的配置类可以拥有多个@Bean的声明。一旦你的配置类的定义,您可以加载并为他们提供Spring容器使用AnnotationConfigApplicationContext如下 -
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
如下您可以加载各种配置类 - 使用的
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
例子:
这里是HelloWorldConfig.java文件的内容
package com.test;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
这里是HelloWorld.java的内容文件
package com.test;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
以下是MainApp的内容。java文件
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}
一旦完成了创建所有源文件并添加了所需的附加库,让我们运行该应用程序。您应该注意,不需要配置文件。如果一切正常您的应用程序,它将打印以下消息 -
Your Message : Hello World!
春天核心参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/ – Ivan