Java 创建非Spring启动对象

Java 创建非Spring启动对象,java,spring-boot,autowired,pojo,Java,Spring Boot,Autowired,Pojo,假设我有一个对象X的模型,这个对象在SpringBoot的帮助下实现了所有CRUD操作 现在,我需要能够使用标准POJO编辑此对象。POJO如下所示: public class Foo { @Autowired private XRepository xDAO; /* Do whatever I want with X and then save it again in the DB using xDAO */ } 到目前为止,我已经尝试过使用@可配

假设我有一个对象X的模型,这个对象在SpringBoot的帮助下实现了所有CRUD操作

现在,我需要能够使用标准POJO编辑此对象。POJO如下所示:

public class Foo {
    @Autowired
    private XRepository xDAO;
    /*
      Do whatever I want with X and then save it again in the DB using xDAO
    */
}
到目前为止,我已经尝试过使用
@可配置的
@组件
甚至
@服务
,但它们都不能
@Autowire
我的
XRepository


我能做什么?

你所描述的是不可能的。只有当对象由Spring管理时,才能连接组件。在您的情况下,它不是,因此不可能在任何依赖项中自动连线。你有多种选择。以下是一些:

  • 在Foo类之外使用存储库。以另一种方式协调操作 由Spring管理的类
  • 将存储库作为依赖项传递给 由Spring管理的类的构造函数中的Foo
  • 这有点老套,可能不推荐使用,但您可以在Foo中将repository设置为静态变量,并通过Spring托管组件在@PostConstruct之类的东西中进行设置

  • 在我看来,最好的办法是使用选项1。

    我认为我没有充分表达自己的观点,不管怎样,我都没有找到解决问题的办法

    解决办法是

    我只是将
    Foo
    声明为
    @服务
    ,然后我只是
    @Autowired
    Foo

    @Autowired
    public class Foo {
    @Autowired
        private XRepository xDAO;
        //some code
    }
    
    然后我使用
    @Autowired
    注释调用这个类

    @Autowired Foo foo
    foo.doThings();
    

    Foo由spring管理吗?XRepository是spring数据存储库吗?Foo不是由spring管理的。如果可能的话,我只想做
    Foo f=new Foo();f、 whatever()
    @Autowired
    将不适用于不受spring管理的对象。您可以将xDAO手动注入到您的Foo中(在SpringDI容器之外):
    Foo-Foo=new-Foo();foo.xDAO=ctx.getBean(XRepository.class)