【问题标题】:Inject bean dynamically? Or @Autowire bean not created by Spring动态注入bean?或者不是由 Spring 创建的 @Autowire bean
【发布时间】:2013-03-17 15:57:17
【问题描述】:

问题:orderRepository = null
据我了解 orderRepository 未注入,因为 user 不是 Spring 创建的 bean,而只是使用 new 创建的对象,然后在 dao 中设置了它的属性?

我将用户设置为活动对象,因此将存储库注入模型类。有什么解决办法,还是有更好的办法?

@Controller
class UserController {
    ...
        // Get user from DB
        User user = userService.findUser(userId);
        Order order = user.findOrder(orderId);
    ...
}

@Component  
User {  
    @Autowired  
    OrderRepository orderRepository;

    Order findOrder(long orderId) {
        Order order = orderRepository
                .findOrderOrThrowException(this.getId(), orderId);
        return order;
    }
}

【问题讨论】:

  • 您是否在 applicationContext.xml 中激活了组件扫描指令? 。 OrderRepository 类是什么样子的?
  • 是的,我得到了这一切,并且应用程序比上面的要大:) 并且在将 repo 注入模型时可以正常工作,除非我从数据库中检索模型类。这个 User bean 在 dao 中创建为 new User(),然后从结果集中填充属性。 Repo 类是常规类,已自动连接到它。

标签: spring-mvc javabeans autowired


【解决方案1】:

User 是由某个存储库创建的,我猜。所以你必须自己注入一个OrderRepository。也许您的 ORM / DB 框架支持拦截器,那么您可以有一个注入 OrderRepository 的中心位置。或者甚至让 Spring 使用注入的 OrderRepository 创建一个空实例,然后框架用数据库中的值填充它。

对于不是由存储库创建的User 实例,Spring 可以完成这项工作。

或者您只是将orderRepository 设为静态成员,恕我直言,这更有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2012-06-04
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多