6

I use spring-boot with spring xml in my project. I wrapper the DAOs in a DataAccessService class to serve as a DB service layer, both the service and the DAOs are injected in spring xml and used by Autowired.

Now I want to have a XXXutils class to provide some static useful functions. Some of the functions need to access the database. But I can't access the DB service or the DAO in static method.

How should I do this? Can I Autowire a static DB service or the DAO in XXXUtils class? May be it not a good practice?

I even don't know whether Spring support the static injection.

Is there any good practice about this?

NingLee
2301 silver badge7 bronze badges
asked Oct 25, 2014 at 4:04

2 Answers 2

6

You can do like this:

public class XXXUtils
{
 @Autowired
 private DataAccessService dsService;
 private static XXXUtils utils;
 @PostConstruct
 public void init()
 {
 utils = this;
 utils.dsService = this.dsService;
 }
 public DataAccessService getDsService()
 {
 return dsService;
 }
 public void setDsService(DataAccessService dsService)
 {
 dsService = dsService;
 }
 public static XXX fun1()
 {
 }
 public static String getDBData()
 {
 return utils.dsService.DsServiceFunc();
 }

Then you can use the XXXXUtils.getDBData() to access the DB.

and in spring xml you can config like this:

<bean id="xxxUtils" class="package of the XXXXUtils" init-method="init">
 <property name="dsService" ref="dsService"/>
</bean>

Hopes this can help you :-)

answered Oct 25, 2014 at 5:08
1
  • It works, Thank you. But I don't know if it is a good practice. Commented Oct 25, 2014 at 6:10
2

The XXXutils static class that has access to the database is a design smell. You shouldn't have static classes with dependencies.

Instead of making it static, just declare it as a Service (given it accesses a DB, it's problably a Service) and then inject it as a dependency in the classes that need it.

Also, please don't use autowired fields. Just inject (i.e. autowire) everything in the constructor. All objects should have all dependencies ready to use in the moment of construction. Anything else is a design smell.

answered Apr 6, 2017 at 14:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.