简体   繁体   中英

Initialize POJO object using Spring

I have some model object or so called POJO object in my application. 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. Eg mostly i declare DAOs, Service, Controller classes as Spring Beans.

But if I will initialize the POJO or even a List object with new keyword I am tightly coupling it to the implementation class.

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.

I thought of using the Application context Aware to do it but then I am tightly coupling my application to Spring.

So my question is

What is the best way to initialize POJO object that it can be extendable later. I prefer to do it using the spring Spring IOC container

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. When someone are going to extend your POJO, they will most likely be capable enough to inject the extension to the relevant services.

If you really want to use Spring, you will have to register a bean in the IoC-container. If you don't want a singleton, you can use @Scope to have Spring instantiate a new instance every time the bean is requested:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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