简体   繁体   English

使用Spring初始化POJO对象

[英]Initialize POJO object using Spring

I have some model object or so called POJO object in my application. 我的应用程序中有一些模型对象或所谓的POJO对象。 Those objects are meant only to store data and will not perform any action. 这些对象仅用于存储数据,不会执行任何操作。

I know that In most cases Spring Beans are not POJOs. 我知道在大多数情况下,Spring Bean不是POJO。 Eg mostly i declare DAOs, Service, Controller classes as Spring Beans. 例如,大多数情况下,我将DAO,Service,Controller类声明为Spring Bean。

But if I will initialize the POJO or even a List object with new keyword I am tightly coupling it to the implementation class. 但是,如果我要使用new关键字初始化POJO或什至是List对象,则将其紧密耦合到实现类。

So if later someone will extend my POJO to add some member variable he will not be able to inject it to the services classes. 因此,如果以后有人将我的POJO扩展为添加一些成员变量,他将无法将其注入服务类。

I thought of using the Application context Aware to do it but then I am tightly coupling my application to Spring. 我考虑过使用应用程序上下文感知来做到这一点,但是随后我将应用程序紧密地耦合到Spring。

So my question is 所以我的问题是

What is the best way to initialize POJO object that it can be extendable later. 可以稍后扩展的初始化POJO对象的最佳方法是什么。 I prefer to do it using the spring Spring IOC container 我更喜欢使用Spring Spring IOC容器

First of all I wouldn'be so concerned about tying code to implementation classes. 首先,我不会太在意将代码绑定到实现类上。 You're correct in that IoC is used to provide flexible points to a code base (extension over modification), but unless you're writing a framework, there's no reason to not use the new keyword to instantiate a POJO. 您是对的,因为IoC用于为代码库提供灵活的点(扩展而不是修改),但是除非您正在编写框架,否则没有理由不使用new关键字实例化POJO。 When someone are going to extend your POJO, they will most likely be capable enough to inject the extension to the relevant services. 当有人要扩展您的POJO时,他们很可能有能力将扩展注入相关服务。

If you really want to use Spring, you will have to register a bean in the IoC-container. 如果您真的想使用Spring,则必须在IoC容器中注册一个bean。 If you don't want a singleton, you can use @Scope to have Spring instantiate a new instance every time the bean is requested: 如果您不希望单例,则可以使用@Scope在每次请求bean时让Spring实例化一个新实例:

@Component
@Scope("prototype")
public class Foo {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM