简体   繁体   中英

Spring DI and creating objects

I want to create an object only if it does not exist on the database. In plain java i would do something like

MyObject getObject(String id) {
       MyObject myObject = myDao.getById(id);
       if(myObject == null) {
           myObject = new MyObject("Some Parameter");
       }
       return myObject;
}

I now want to use Spring for this. My idea is using a Factory that is injected beforehand. Something in the direction of (but with constructor injection):

@Autowired
MyObjectFactory myObjectFactory;

MyObject getObject(String id) {
       MyObject myObject = myDao.getById(id);
       if(myObject == null) {
           myObject = myObjectFactory.newInstance("Some Parameter");
       }
       return myObject;
}

But to be sure I wanted to ask what options there are and which method is preferred going in line with Springs DI.

* EDIT 1 * Fixed Autowired annotation

* EDIT 2 * Copyinf from one of my comments

I have to have a bit more logic in the getObject method than shown here.

I have to check for different unique keys to find a matching object, and only if I find no object with the different approaches, then I will create a new one. I just kept the code small for the question. This is why I would rather not use the create if not found approach.

Also I try to keep the code testable and abstract the object creation from the method.

"I want to create an object only if it does not exist on the database ."

I think you can use repository to check if there is object with that id if not - then create it.

To use repository use eg:

 @Autowired
 private PersonRepository repository;

then check if element exists use:

repository.findOne(id);

Is something wrong with that approach?

Spring repository:

http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

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