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
@Component
public final class GeneUtil {
Defining logmongotemplate in XML
<mongo:db-factory id="logMongoDbFactory"
host="${mongo.log.server}"
port="${mongo.log.port}"
dbname="${mongo.log.db}"
username="${mongo.log.user}"
password="${mongo.log.password}"/>
<bean id="logMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="logMongoDbFactory"/>
</bean>
Similar Posts:
- [Solved] expected single matching bean but found 2
- Spring cloud uses feignclient to start and report an error
- Consider defining a bean of type ‘xxx’ in your configuration. Autowired(required=true)
- How to Solve MongoDB Error: Authentication failed.
- Container Cannot Find bean, Field usersMapper in com.imooc.impl.UserServiceImpl required a bean of type ‘com.imooc.mapper.UsersMapper’ that could not be found.
- Cannot resolve reference to bean ‘entityManagerFactory’ while setting constructor argument
- Java error: No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- Mongodb access control is not enabled for the database
- Springboot Error: Failed to configure a DataSource: ‘url’ attribute is not specified and no embedd
- [Solved] org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type