Spring – Issues About Static Injection in Spring

dependency-injectionspringstatic-access

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?

Best Answer

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 :-)

Related Topic