Solve the problem that SpringMvc non-controller classes use @Autowired annotation service injection to be null

Original address: http://blog.sina.com.cn/s/blog_98721cfd0102xj96.html

Using the SpringMVC framework, there are some tool classes and static non-controller classes that need to call the service layer managed by spring during the development process. However, using the @Autowired annotation to inject the Service, a null exception will be reported; I searched for some methods on the Internet, and actually tested it, and found that there is something missing from the Internet, so I will summarize and write it down as a study note, and I hope Can help other children's shoes who encounter this problem~ Well, let's talk about the specific implementation steps:
1. Add the scan configuration of the package where the tool class is located in the configuration file (springmvc.xml). When I first transformed it according to the online statement, it was always null because there was no configuration here. "com.zzzy.bms.util" is the package path where my utility class is located

2. Transformation tool class, the code here is copied from other great gods on the Internet, I added a little comment
@Component// declare the tool class as a spring component, this must not be forgotten
public class TestUtils {
@Autowired
private ItemService itemService;

@Autowired
// private ItemMapper itemMapper;

// statically initialize the current class
public static TestUtils testUtils;

// Add the annotation @PostConstruct to the method, so that the method will be executed by the Spring container after the bean is initialized (Note: Bean initialization includes, instantiating the bean, and assembling the properties of the bean (dependency injection)).
@PostConstruct
public void init() {
testUtils = this;
}

// Examples of methods using the service or mapper interface in the utils tool class, just use "testUtils.xxx. method"
public static void test(Item record) {
// method to call service
testUtils.itemService.insert(record);
}
}
Well, the above is my transformation process~ I passed the test in my own project.

There are some other methods, which are also recorded here, but have not been tested. I don't think it conforms to the usage habits of springmvc:
//applicationContext-service.xml is the name of the configuration file that declares the service
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-service.xml");
//"userService" is the ID of the service defined in the configuration file,
UserService uService = ( UserService ) ac.getBean("userService"); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325503382&siteId=291194637