When a class contains the @autowired subclass, he is to be handed to the spring to handle and cannot use the new to initialize, otherwise he will lead to the automatic assembly of subclass is null,
So the call to the class, besides it also autowire, are there any other way, examples are as follows:
This is my part of the service class, in which he dao class is automatic assembly:
@ Service
Public class CategoryService {
The @autowired
Private CategoryDAO CategoryDAO;
}
The service class is invoked in the RecordListener:
Public class RecordListener implements ActionListener {
Public void actionPerformed (an ActionEvent e) {
If (new CategoryService (). The list (). The size ()==0) {
.
}
In addition to automatic assembly CategoryService class again in this class, what other ways can obtain CategoryService? Is it must use ApplicationContext to get, thank you!
CodePudding user response:
If you use the spring to provide annotations or XML configuration bean, can only use ApplicationContext to obtain, spring provides extension points, you can go to register beans, publishing events, etcCodePudding user response:
If the class, do not rely on other Spring bean or configuration,You can direct the new CategoryService
But because your CategoryService rely on CategoryDAO, so no,
So so, so a lot of coding standards, are not recommended Autowired, but it is recommended to use a constructor, such as:
@ Service
Public class CategoryService {
Private final CategoryDAO CategoryDAO;
Public CategoryService (CategoryDAO CategoryDAO) {
Enclosing categoryDAO=categoryDAO;
}
}
So write, outside you can direct the new CategoryService (dao)