Problems encountered today is to create a generic class. By @Component Note, this class is added to the vessel, and thus some of the operations performed,
Mapper can be injected save data to the database.
But when I do, use @Autowired has been reported null exception, and then I wonder, how not injected into it. Not injected into it will be reported null exception.
Then I Baidu looking for information, and finally found the problem I encountered wanted to use comrades.
The final solution is removed @Component annotation, in the instance of this class, taken from the spring in the context instance to be assigned to the Bean
The definition of member variables.
Such as:
Define a utility class ApplicationContextProvider
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/ **
* returns specified by name, and Bean Clazz
*
* @param name
* @param clazz
* @param <T>
* @return
* /
public static <T> T the getBean (String name, Class <T> clazz) {
return getApplicationContext () the getBean (name, clazz);.
}
}
In a specific implementation class then:
public class text{
private ChatMessageMapper chatMessageMapper;
public text() {
this.chatMessageMapper = ApplicationContextProvider.getBean(ChatMessageMapper.class);
}
/*