When spring injects static object properties, it is not possible to use @Autowired directly on the property because of the virtual machine class loading problem . You need to @autowired on the set method that corresponds to the property, and the set method cannot be defined as static.
1. Create a class for static object properties
Package Com.bluej.springj.service.impl; Import Org.springframework.stereotype.Service; Import Com.bluej.springj.service.LogService; @Service ("Logservice") Public class Implements Logservice { publicvoid Dolog () { System.out.println (" Logserviceimpl.dolog ");} }
Logservice Class Code
2. Creating objects that Spring uses
1 PackageCom.bluej.springj.service.impl;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 ImportOrg.springframework.stereotype.Service;5 6 ImportCom.bluej.springj.service.CheckService;7 ImportCom.bluej.springj.service.LogService;8 9@Service ("Checkservice")Ten Public classCheckserviceimplImplementsCheckservice { One A Private StaticLogservice Logservice; - - Public BooleanDocheck (Object obj) { theSystem.out.println ("Checkserviceimpl.docheck"); - Logservice.dolog (); - return false; - } + - @Autowired + Public voidSetlogservice (Logservice logservice) { ACheckserviceimpl.logservice =Logservice; at } -}
Checkserviceimpl class
3. Invoking the sample
1 PackageCom.bluej.springj.start;2 3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 ImportCom.bluej.springj.service.CheckService;7 8 Public classMain {9 Public Static voidMain (string[] args) {TenApplicationContext ApplicationContext =NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); OneCheckservice Checkservice = Applicationcontext.getbean ("Checkservice", Checkservice.class); ACheckservice.docheck (NewObject ()); - } -}
Main class
4. Code Address
Git address: https://git.oschina.net/blue_phantom/ssmj.git
Project Name: SPRINGJ
Pack Location: Package Com.bluej.springj.start
Execution Test class: Main.java
Spring Learning--injecting static object properties