在Spring文档中说@Bean
annotation can be applied to methods even in components and POJOs。
但是如何实例化这些bean?
以下代码抛出NoSuchBeanDefinitionException
。它还表明,当调用方法时,bean会被构造几次(这与关于检测的单词一致,但与关于范围的单词不一致)。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class LiteModeBeans {
public static class Database {
}
public static class MyClass {
{
System.out.println("Constructed");
}
private Database database;
public Database getDatabase() {
return database;
}
@Autowired
public void setDatabase(Database database) {
this.database = database;
System.out.println("Database set");
}
}
public static class LiteContainingBean {
@Bean
MyClass myClass() {
return new MyClass();
}
public MyClass getMyClass() {
return myClass();
}
}
@Configuration
public static class Config {
@Bean
Database database() {
return new Database();
}
@Bean
LiteContainingBean liteContainingBean() {
return new LiteContainingBean();
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
MyClass myClass;
LiteContainingBean liteContainingBean = ctx.getBean(LiteContainingBean.class);
myClass = liteContainingBean.myClass();
myClass = liteContainingBean.myClass();
myClass = ctx.getBean(MyClass.class); // No qualifying bean of type [com.inthemoon.snippets.springframework.LiteModeBeans$MyClass] is defined
System.out.println("MyClass: " + myClass.toString());
}
}
那么,如何通过Spring创建和处理MyClass
的bean?
更新
以下工作,谢谢@MDeinum
:
public class LiteModeBeans {
public static class Database {
}
public static class MyClass {
{
System.out.println("Constructed");
}
private Database database;
public Database getDatabase() {
return database;
}
@Autowired
public void setDatabase(Database database) {
this.database = database;
System.out.println("Database set");
}
}
@Component
public static class LiteContainingBean {
@Bean
MyClass myClass() {
return new MyClass();
}
}
@Configuration
public static class Config {
@Bean
Database database() {
return new Database();
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, LiteContainingBean.class);
MyClass myClass;
myClass = ctx.getBean(MyClass.class); // No qualifying bean of type [com.inthemoon.snippets.springframework.LiteModeBeans$MyClass1] is defined
System.out.println("MyClass1: " + myClass.toString());
}