Spring annotation and spring Annotation
Address: http://casheen.iteye.com/blog/295348
1. Inject attributes using Spring annotations
1. How do we inject attributes before using annotations?
Class implementation:
Java code
- Public class UserManagerImpl implements UserManager {
- Private UserDao userDao;
- Public void setUserDao (UserDao userDao ){
- This. userDao = userDao;
- }
- ...
- }
Configuration file:
Java code
- <Bean id = "userManagerImpl" class = "com. kedacom. spring. annotation. service. UserManagerImpl">
- <Property name = "userDao" ref = "userDao"/>
- </Bean>
- <Bean id = "userDao" class = "com. kedacom. spring. annotation. persistence. UserDaoImpl">
- <Property name = "sessionFactory" ref = "mySessionFactory"/>
- </Bean>
1. 2. Introduce @ Autowired annotation (not recommended. @ Resource is recommended)
Class implementation (tagging member variables)
Java code
- Public class UserManagerImpl implements UserManager {
- @ Autowired
- Private UserDao userDao;
- ...
- }
Or (mark the method)
Java code
- Public class UserManagerImpl implements UserManager {
- Private UserDao userDao;
- @ Autowired
- Public void setUserDao (UserDao userDao ){
- This. userDao = userDao;
- }
- ...
- }
Configuration File
Java code
- <Bean id = "userManagerImpl" class = "com. kedacom. spring. annotation. service. UserManagerImpl"/>
- <Bean id = "userDao" class = "com. kedacom. spring. annotation. persistence. UserDaoImpl">
- <Property name = "sessionFactory" ref = "mySessionFactory"/>
- </Bean>
@ Autowired can mark member variables, methods, and constructors to complete automatic assembly. In the preceding two different implementation methods, @ Autowired has different annotation positions. They will automatically assemble the userDao attribute when Spring initializes the bean userManagerImpl. The difference is: in the first implementation, spring directly assigns a unique bean Of The UserDao type to the userDao member variable. In the second implementation, spring will call the setUserDao method to assemble the only bean Of The UserDao type into the userDao attribute.
. Let @ Autowired work
To enable @ Autowired to work, add the following code to the configuration file:
Java code
- <Bean class = "org. springframework. beans. factory. annotation. AutowiredAnnotationBeanPostProcessor"/>
1. 4. @ Qualifier
@ Autowired is automatically assembled Based on the type. In the preceding example, if more than one bean of the UserDao type exists in the Spring context, the BeanCreationException is thrown. If the bean of the UserDao type does not exist in the Spring context, beanCreationException will also be thrown. We can use @ Qualifier with @ Autowired to solve these problems.
1. There may be multiple UserDao instances
Java code
- @ Autowired
- Public void setUserDao (@ Qualifier ("userDao") UserDao userDao ){
- This. userDao = userDao;
- }
In this way, Spring finds the bean whose id is userDao for assembly.
2. The UserDao instance may not exist.
Java code
- @ Autowired (required = false)
- Public void setUserDao (UserDao userDao ){
- This. userDao = userDao;
- }
1. 5. @ Resource (JSR-250 standard annotation, it is recommended to use it to replace Spring proprietary @ Autowired annotation)
Spring not only supports self-defined @ Autowired annotations, but also supports several annotations defined by JSR-250 specifications, which are @ Resource, @ PostConstruct, and @ PreDestroy.
@ Resource is equivalent to @ Autowired, but @ Autowired is automatically injected by byType, while @ Resource is automatically injected by byName by default. @ Resource has two attributes, namely name and type. Spring resolves the name attribute of @ Resource annotation to the bean name, And the type attribute to the bean type. Therefore, if the name attribute is used, the automatic injection policy of byName is used, and the automatic injection policy of byType is used when the type attribute is used. If neither name nor type is specified, the byName automatic injection policy is used through reflection.
@ Resource Assembly Sequence
. @ PostConstruct (JSR-250)
Add the annotation @ PostConstruct to the method. This method will be executed by the Spring container after Bean initialization (Note: Bean initialization includes instantiating Bean, and assemble Bean attributes (dependency injection )).
A typical application scenario is that when you need to inject an attribute defined in the parent class into the Bean, and you cannot rewrite the attributes of the parent class or the setter method of the attribute, for example:
Java code
- Public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
- Private SessionFactory mySessionFacotry;
- @ Resource
- Public void setMySessionFacotry (SessionFactory sessionFacotry ){
- This. mySessionFacotry = sessionFacotry;
- }
- @ PostConstruct
- Public void injectSessionFactory (){
- Super. setSessionFactory (mySessionFacotry );
- }
- ...
- }
Here, @ PostConstruct is used to inject the sessionFactory private attribute defined in the UserDaoImpl parent class into our own sessionFactory (the setSessionFactory method of the parent class is final and cannot be rewritten ), then we can call super. getSessionFactory () to access this attribute.
1. 7. @ PreDestroy (JSR-250)
Add the annotation @ PreDestroy to the method. This method will be executed by the Spring container after Bean initialization. We do not need to use it for the moment, so we will not describe it here. Its usage is the same as @ PostConstruct.
. Use <context: annotation-config/> to simplify the configuration
Spring2.1 adds a Schema namespace for the new context, which provides convenient configuration for the annotation driver, attribute file introduction, and loading period weaving functions. We know that the annotation itself does not do anything, and it only provides metadata information. To make the metadata really take effect, the processor responsible for processing the metadata must work.
AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are the processors that process the annotation metadata. However, defining these beans in the Spring configuration file is clumsy. Spring provides us with a convenient way to register these BeanPostProcessor, Which is <context: annotation-config/>:
Java code
- <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context"
- Xsi: schemaLocation = "http://www.springframework.org/schema/beans
- Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- Http://www.springframework.org/schema/context
- Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
- <Context: annotation-config/>
- </Beans>
<Context: annotationconfig/> the AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, and RequiredAnnotationBeanPostProcessor will be implicitly registered with the Spring container.
2. Use Spring annotations to define beans
The above section describes how to implement automatic injection in Bean through @ Autowired or @ Resource. Next we will introduce how to annotate Bean to completely remove Bean-defined configuration from the XML configuration file.
2. 1. @ Component (not recommended), @ Repository, @ Service, @ Controller
You only need to add a @ Component annotation to the corresponding class to define the class as a Bean:
Java code
- @ Component
- Public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
- ...
- }
For the Bean defined using the @ Component annotation, the default name (id) is an unqualified class name starting with lowercase. For example, the Bean name defined here is userDaoImpl. You can also specify the Bean Name:
@ Component ("userDao ")
@ Component is a common form of all Spring management components. Spring also provides more refined annotation forms: @ Repository, @ Service, and @ Controller, which correspond to the storage layer beans respectively, service layer Bean and presentation layer Bean. In the current version (2.5), these annotations have the same semantics as @ Component and are completely universal. In Versions later than Spring, more semantics may be added to them. Therefore, we recommend @ Repository, @ Service, and @ Controller to replace @ Component.
2. Use <context: component-scan/> to make Bean definition annotations work.
Java code
- <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context"
- Xsi: schemaLocation = "http://www.springframework.org/schema/beans
- Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- Http://www.springframework.org/schema/context
- Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
- <Context: component-scan base-package = "com. kedacom. ksoa"/>
- </Beans>
Here, all the configuration content of bean defined through the <Bean> element has been removed. You only need to add one <context: the component-scan/> Configuration solves all the problems-the Spring XML configuration file is simplified to the extreme (of course, the configuration metadata is still needed, but it only exists in the form of annotations ). <Context: component-scan/> specifies the class package to be scanned. All classes in the class package and Its Recursive Sub-package are processed.
<Context: component-scan/> also allows you to define filters to include or exclude certain classes in the base package. Spring supports the following four types of filtering methods:
- Examples of filter type expressions
- Annotation org. example. SomeAnnotation filters out all classes using the SomeAnnotation annotation.
- The class name specifies org. example. SomeClass to filter the specified class.
- Regular Expression com \. kedacom \. spring \. annotation \. web \. * filter some classes by Regular Expression
- AspectJ expression org. example... * Service + filter some classes using AspectJ expressions
Taking a regular expression as an example, I will list an application example:
Java code
- <Context: component-scan base-package = "com. casheen. spring. annotation">
- <Context: exclude-filter type = "regex" expression = "com \. casheen \. spring \. annotation \. web \ .. *"/>
- </Context: component-scan>
It is worth noting that the <context: component-scan/> configuration item not only enables scanning of class packages to implement the annotation-driven Bean definition function, the annotation driver automatic injection function is also enabled (that is, AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are implicitly registered internally). Therefore, when <context: component-scan/> is used, you can remove <context: annotation-config/>.
2. 3. Use @ Scope to define the Bean Scope
When using XML to define beans, we may also need to define the scope of a Bean through the Scope attribute of bean. We can also do this through the @ scope annotation:
Java code
- @ Scope ("session ")
- @ Component ()
- Public class UserSessionBean implements Serializable {
- ...
- }
3. Reference
Http://kingtai168.iteye.com/blog/244002
Http://www.iteye.com/topic/244153
Http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config
Http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classpath-scanning
Notes on how to configure Spring3
• @ Controller
• @ Service
• @ Autowired
• @ RequestMapping
• @ RequestParam
• @ ModelAttribute
• @ Cacheable
• @ CacheFlush
• @ Resource
• @ PostConstruct
• @ PreDestroy
• @ Repository
• @ Component (not recommended)
• @ Scope
• @ SessionAttributes
• @ InitBinder
• @ Required
• @ Qualifier
@ Controller
• Example
@ Controller
Public class SoftCreateController extends SimpleBaseController {}
• Or
@ Controller ("softCreateController ")
• Description
@ Controller registers a bean to the spring context. bean IDs start with the class name and start with lowercase letters by default.
@ Service
• Example
@ Service
Public class SoftCreateServiceImpl implements ISoftCreateService {}
• Or
@ Service ("softCreateServiceImpl ")
• Description
@ Service registers a bean to the spring context. bean IDs start with the class name and start with lowercase letters by default.
@ Autowired
• Example
@ Autowired
Private ISoftPMService softPMService;
• Or
@ Autowired (required = false)
Private ISoftPMService softPMService = new SoftPMServiceImpl ();
... The remaining full text>
What is @ component in spring annotation?
At the persistence layer, business layer, and control layer, @ Repository, @ Service, and @ Controller are used to comment out classes in the hierarchy, while @ Component is used to comment out the neutral classes.
The class is handed over to Spring management and named userManager again. It is hard to say which layer the class belongs to, so @ Component is used.