Surasin Tancharoen
Surasin Tancharoen

Reputation: 5850

How to get an object with transaction in Spring?

I have a Service class like this:

@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyDAO companyDAO;

    @Transactional
    public void addOrUpdateCompany(Company company) {
        companyDAO.addOrUpdateCompany(company);
    }

}

Normally, I can have an instance of CompanyService from Spring by:

@Autowired
CompanyService companyService;

But, in some cases, I want to create/get an instalce of CompanyService without @Autowired like this:

CompanyService companyService  = XXX.getxxx("CompanyService");

Is there any ways I can do this?

Upvotes: 1

Views: 307

Answers (3)

chalimartines
chalimartines

Reputation: 5653

Other way is


@Component
public class ContextHolder implements ApplicationContextAware {
    private static ApplicationContext CONTEXT;

    public void setApplicationContext(ApplicationContext applicationContext) {
        CONTEXT = applicationContext;
    }

    public static ApplicationContext getContext() {
        return CONTEXT;
    }
}

And then

CompanyService service = ContextHolder.getContext().getBean(CompanyService.class);

Upvotes: 2

Henrique Miranda
Henrique Miranda

Reputation: 994

You can do it. You need to instancate the application context and then get your been.

Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
    new String[] {"applicationContext.xml", "applicationContext-part2.xml"});
// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;

and use:

MyObject my = (MyObject)factory.getBean(NAME_OF_YOUR_BEAN);

Upvotes: 1

Ido.Co
Ido.Co

Reputation: 5507

If I understand you correctly, you mean something like - ServiceLocatorFactoryBean with it you can call somthing like MyService getService(String id)).

Another way, will be to implement some kind of a controller service that will have all other services autowired to it, and will hold a map from their string id to actual instances.

In my opinion the second option is better, since it's more manageable and clear.

Hope that helps you.

Upvotes: 2

Related Questions