【问题标题】:how to autowire spring beans from a non-bean object created at runtime?如何从运行时创建的非 bean 对象中自动装配 spring bean?
【发布时间】:2016-04-07 20:27:32
【问题描述】:
我有一些 Jpa 存储库和几个实体类。我需要为我的一个实体创建一个辅助对象。在那个助手中,我使用@Autowire 来访问 Jpa 存储库。
@Entity
class A {
@Transient
Helper helper;
...
}
class Helper {
A a;
@Autowired
CRepository repo;
public Helper(A a) {
this.a = a;
}
}
但是,repo 始终为空。我尝试过使用 SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this) 和 @Configurable,但它们都失败了。谁能给我一些提示?
顺便说一句,A 在休息控制器中被实例化。
谢谢!
【问题讨论】:
标签:
spring
autowired
configurable
【解决方案1】:
您可以使用 BeanUtil 类来获取在 Springl 中创建的任何 bean
@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
然后你就可以拿到豆子了。
MyBean obj = BeanUtil.getBean(MyBean.class);
【解决方案2】:
使用构造函数注入代替字段注入;无论如何,这一直是最佳实践。然后将A 注入控制器并将其作为构造函数参数传递就很简单了。
【解决方案3】:
@Configurable 注解可以正常工作,但是您需要在任何配置类中使用@EnableSpringConfigured 注解才能使其工作。在其他 stackoverflow 帖子中阅读我的答案:spring autowiring not working from a non-spring managed class
实体类不应包含任何助手,即使是暂时的。对于干净的设计,您需要分离关注点,因此实体不应该知道您的业务逻辑。我无法为您提供更多帮助,因为我不知道该帮助者的目标是什么,但在这里您还有其他选择:
ALTERNATIVE 1(根据您的描述,helper 似乎是一个有状态的 bean,所以它不是@Service 的候选者,我个人认为应该是)
@Controller
public MyController {
@RequestMapping(...)
public void processRequest() {
A a = new A();
...
Helper helper = new Helper(a); // CRepository is successfully autowired
}
}
@Configurable(autowire = Autowire.BY_TYPE)
public class Helper {
A a;
@Autowired
CRepository repo;
}
@Configuration
@EnableSpringConfigured
public Application {
...
}
ALTERNATIVE 2(使您的 Helper 类无状态,以便 spring 知道您的 bean,而无需像 @Confgurable/@EnableSpringConfigured 这样的额外内容)
@Controller
public MyController {
@Autowired Helper helper; // CRepository is correctly autowired
@RequestMapping(...)
public void processRequest() {
A a = new A();
...
helper.doSomething(a);
}
}
@Service
public class Helper {
// A a; remove dependency to A to make it stateless
@Autowired
CRepository repo;
public Helper() {
}
public void doSomething(A a) {
...
repo.save(a);
}
}
【解决方案4】:
您不能在 Helper 类中自动装配任何内容,因为它不是由 Spring 管理的。
您可以使用这种方法:
public class HelperManager {
@Autowired
private ApplicationContext context;
public Helper getHelper(A a) {
return context.getBean(Helper.class, a);
}
将 Helper 配置为原型 bean:
@Configuration
public class MyConfiguration {
@Bean
public HelperManager helperManager() {
return new HelperManager();
}
@Bean
@Scope("prototype")
public Helper helper(A a) {
return new Helper(a);
}
}
最后在你的控制器中:
@Controller
public class MyController {
@Autowired
private HelperManager helperManager;
public someMethodWhereToInstanceYourHelper(A a) {
...
Helper helper = helperManager.getHelper(a);
...
}
}