[Solved] Cannot make a static reference to the non-static field logMongoTemplate

Sometimes we need to use spring injected database instances in static methods

However, instance variables injected through @ Autowired cannot be directly used in static methods

You will be prompted not to make a static reference to the non static field logmongotemplate

The solution is as follows. The general idea is to create a static instance and assign the database instance injected by @ Autowired to the static instance in init method

Add scan in XML

<context:component-scan base-package="com.data.util"/>

Add Component annotation in Java file

public final class GeneUtil {

Defining logmongotemplate in XML

  <mongo:db-factory id="logMongoDbFactory"    
     <bean id="logMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     	 <constructor-arg name="mongoDbFactory" ref="logMongoDbFactory"/>  

Similar Posts: