Java Static file usage annotations

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.