Home > Back-end >  In the spring using the @autowired class how to be called
In the spring using the @autowired class how to be called

Time:09-22

Good bosses, I began to study application of spring, an automatic assembly related problems,
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, etc

CodePudding 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)
  • Related