Java 是否可以将自己在运行时动态创建的对象注册为Springbean?
我需要使用SpringAOP工具,不希望为了拦截对一个对象的方法调用而进行AspectJ集成,因为该对象最初不是Springbean。对象将在运行时动态创建。我无法将bean定义添加到Java 是否可以将自己在运行时动态创建的对象注册为Springbean?,java,spring,aop,Java,Spring,Aop,我需要使用SpringAOP工具,不希望为了拦截对一个对象的方法调用而进行AspectJ集成,因为该对象最初不是Springbean。对象将在运行时动态创建。我无法将bean定义添加到ApplicationContext配置文件中。那么spring是否提供了这样的设施 是的,这是可能的。您可以使用@bean和@Scope(ConfigurableBeanFactory.Scope\u prototype)在@Configurationbean中创建一个原型范围的bean,该bean将充当工厂:
ApplicationContext
配置文件中。那么spring是否提供了这样的设施 是的,这是可能的。您可以使用@bean
和@Scope(ConfigurableBeanFactory.Scope\u prototype)
在@Configuration
bean中创建一个原型范围的bean,该bean将充当工厂:
@Configuration
public class Factory {
public static class A {
private final int x;
public A(int x) {
this.x = x;
}
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Autowired
public A getA(int arg) {
try {
return A.class.getConstructor(int.class).newInstance(arg);
} catch (Exception e) {
throw new BeanCreationException("A" + arg, "Could not create instance of bean A", e);
}
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public int getArg() {
return (int) (Math.random() * 2 + 1);
}
@PostConstruct
public void test() {
int r1 = this.getArg();
A a1 = this.getA(r1);
System.out.println("a1.x = " + a1.x); // 1 or 2
int r2 = this.getArg();
A a2 = this.getA(r2);
System.out.println("a2.x = " + a2.x); // 2 or 1, different to a1.x
}
}
在方法getA()
请注意,从Spring4.x版本开始,您可以使用@Autowired
自动连接要由@bean
方法返回的bean参数,这意味着这些参数可以是其他bean,甚至是基本类型的bean。这就是为什么我将A
bean的参数设置为原型范围的bean
然后在@PostConstruct
方法中(我使用它作为测试),我得到int
参数的两个实例和a
bean的两个实例,并将它们分配给a
的每个实例
如果我没有使用@Scope(ConfigurableBeanFactory.Scope\u PROTOTYPE)
注释,那么getArg()
和getA(arg)
@Bean
方法在第二次调用时都会返回相同的实例,因为Spring对Bean的默认作用域是ConfigurableBeanFactory.Scope\u SINGLETON
。如果这是您期望的行为,只需删除@Scope
注释。如果您创建prototype Scope bean holder,可以在其中设置新创建的对象,该怎么办?你需要豆子吗?不需要。。。Spring只能将AOP应用于SpringBean。YOU可以注册一个单例,但不会被代理。为什么不可能将bean添加到spring上下文中,将其定义为原型范围,并使用BeanFactory
作为工厂来创建bean.@M.Deinum,因为该类只是一个Java类,与我们通常在上下文中定义的DAO、服务和QuartzScheduler无关。我认为在应用程序环境中混入此类课程不是一个好主意。我只想截获一个方法调用并做一些事情。AspectJ是否必要?如果您不想注册它,这是您唯一的选择。但是为什么不简单地注册它并将上下文用作工厂呢。您可以创建自己的工厂来包装BeanFactory
或ApplicationContext
以便限制代码中Spring依赖项的数量。比在代码中引入加载或编译时编织要容易得多。戴纳姆是对的。您必须走一条路:SpringAOP的Spring路或AspectJ的POJO路。你不淋湿就不能洗澡。