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?

2 Answers 2


You can do like this:

public class XXXUtils

    private DataAccessService dsService;

    private static XXXUtils utils;

    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"/>

Hopes this can help you :-)

  • It works, Thank you. But I don't know if it is a good practice.
    – shangyin
    Oct 25, 2014 at 6:10

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.