Spring annotation and spring Annotation

Source: Internet
Author: User

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
  1. Public class UserManagerImpl implements UserManager {
  2. Private UserDao userDao;
  3. Public void setUserDao (UserDao userDao ){
  4. This. userDao = userDao;
  5. }
  6. ...
  7. }


Configuration file:

Java code
  1. <Bean id = "userManagerImpl" class = "com. kedacom. spring. annotation. service. UserManagerImpl">
  2. <Property name = "userDao" ref = "userDao"/>
  3. </Bean>
  4. <Bean id = "userDao" class = "com. kedacom. spring. annotation. persistence. UserDaoImpl">
  5. <Property name = "sessionFactory" ref = "mySessionFactory"/>
  6. </Bean>



1. 2. Introduce @ Autowired annotation (not recommended. @ Resource is recommended)
Class implementation (tagging member variables)

Java code
  1. Public class UserManagerImpl implements UserManager {
  2. @ Autowired
  3. Private UserDao userDao;
  4. ...
  5. }


Or (mark the method)

Java code
  1. Public class UserManagerImpl implements UserManager {
  2. Private UserDao userDao;
  3. @ Autowired
  4. Public void setUserDao (UserDao userDao ){
  5. This. userDao = userDao;
  6. }
  7. ...
  8. }


Configuration File

Java code
  1. <Bean id = "userManagerImpl" class = "com. kedacom. spring. annotation. service. UserManagerImpl"/>
  2. <Bean id = "userDao" class = "com. kedacom. spring. annotation. persistence. UserDaoImpl">
  3. <Property name = "sessionFactory" ref = "mySessionFactory"/>
  4. </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
  1. <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
  1. @ Autowired
  2. Public void setUserDao (@ Qualifier ("userDao") UserDao userDao ){
  3. This. userDao = userDao;
  4. }


In this way, Spring finds the bean whose id is userDao for assembly.
2. The UserDao instance may not exist.

Java code
  1. @ Autowired (required = false)
  2. Public void setUserDao (UserDao userDao ){
  3. This. userDao = userDao;
  4. }



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
  1. Public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
  2. Private SessionFactory mySessionFacotry;
  3. @ Resource
  4. Public void setMySessionFacotry (SessionFactory sessionFacotry ){
  5. This. mySessionFacotry = sessionFacotry;
  6. }
  7. @ PostConstruct
  8. Public void injectSessionFactory (){
  9. Super. setSessionFactory (mySessionFacotry );
  10. }
  11. ...
  12. }


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
  1. <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"
  2. Xsi: schemaLocation = "http://www.springframework.org/schema/beans
  3. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  4. Http://www.springframework.org/schema/context
  5. Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
  6. <Context: annotation-config/>
  7. </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
  1. @ Component
  2. Public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
  3. ...
  4. }


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
  1. <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"
  2. Xsi: schemaLocation = "http://www.springframework.org/schema/beans
  3. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  4. Http://www.springframework.org/schema/context
  5. Http://www.springframework.org/schema/context/spring-context-2.5.xsd>
  6. <Context: component-scan base-package = "com. kedacom. ksoa"/>
  7. </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
  1. <Context: component-scan base-package = "com. casheen. spring. annotation">
  2. <Context: exclude-filter type = "regex" expression = "com \. casheen \. spring \. annotation \. web \ .. *"/>
  3. </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
  1. @ Scope ("session ")
  2. @ Component ()
  3. Public class UserSessionBean implements Serializable {
  4. ...
  5. }



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.

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.