The spring framework brings great convenience to the writing of our code, especially the use of annotations. But there is a problem, when we use annotations in static files, this time will be an error. such as the following code:
@Autowired
Private UserService UserService;
Public Static int Test (user user) { returnint i = userservice.adduser (user);}
If this is not a problem in the normal code, but put in the static code block there will be a problem. because static code allocates memory when the project is started, there is no data in the UserService.
To solve this problem, we can use the following methods:
@Component//Refer to the component, we can use this annotation to annotate when the component is not well categorized
Public classFreezeutil {@AutowiredPrivateUserService UserService; Private StaticFreezeutil Freezeutil; @PostConstruct//@PostConstruct modified method will run when the server loads Servle and will only be executed once by the server. Postconstruct executes after the constructor, before the Init () method executes Public voidinit () {Freezeutil= This; Freezeutil.userservice= This. UserService; } PublicUserService Getuserservice () {returnUserService; } Public voidSetuserservice (UserService userservice) { This. UserService =UserService; } }
Use the following:
Public Static int Test (user user) { // Note is freezeutil.userservice instead of UserService return int i = freezeUtil.userService.addUser (user); }
Java Static file usage annotations