Spring (12)-Bean Injection Using Annotation

Source: Internet
Author: User

Spring (12)-Bean Injection Using Annotation

In the previous blog posts, bean injection is configured in xml, and Boyou's requirements are added, so we decided to give a simple explanation of the annotation method, it won't involve too complex programs here, because the purpose of this article is to let the majority of bloggers who see this blog post understand it, rather than reading it in the fog.

Common annotations

1. @ Controller: Mark the class of a Controller component.

2. @ Service: class for marking a business logic component.

3. @ Repository: class for marking a Dao component.

4. @ Component: Mark a common class.

These annotations are mainly used to mark the classes to be instantiated by Spring. Once such annotation is added to a class, if it is in the singleton mode, then during Spring initialization, these classes will be instantiated. For classes that are not in the singleton mode, they do not depend on the Spring container itself. They are often created when the client initiates a request (created by Spring ), these have been described in previous blog posts. Please refer to Spring advanced path (7)-Bean lifecycle and creation and destruction execution processes.

5. @ Resource: inject by name. This annotation is a jdk annotation, but it is widely used in projects.

6. @ Autowired: Automatic Injection Based on type matching.

The two annotations here are mainly used to inject values for attributes in the class. The two annotations can inject (the objects instantiated by the classes marked by the preceding four annotations in Spring) into some class attributes.

7. @ Scope ("prototype"): by default, a singleton object is generated. After the prototype parameter is passed in the Scope, it indicates that this class is not Singleton, it is "Multi-sample". Readers can correct it if they do not know the standard of such interpretation.

8. @ PostConstruct: The Initialization Method of the specified bean works the same as the initMethod specified in the configuration file in the previous blog post (Spring advanced path (7)-Bean lifecycle and creation and destruction execution processes ), spring calls back this method after Bean dependency injection is complete.

9. @ PreDestroy: specify the method before bean destruction and the Spring advanced path (7) -The role of the destroyMethod specified in the configuration file in the Bean life cycle and execution process for creation and destruction is the same in this blog post. It will be called before bean destruction.

 

In addition:

10: @ Lazy: Specifies whether the class cancels pre-initialization. The parameter 'boolean' can be specified to be 'true'. We will not describe it here. This annotation is relatively simple.

11: @ DependsOn: class or method that can be modified to force initialization of some beans, for example? A class = "_ cf_email _" href = "/cdn-cgi/l/email-protection" data-cfemail = "4fa8ecf50f0b2a3f2a212b3c0021"> [email protected] ({"wy ", "wangyang"}), so that the bean in the initialization will be forcibly initialized before initialization.

Instance demo

The prerequisite for automatic bean Injection Using annotations is that automatic injection is configured in the configuration file.

 

 
 
  
  
 

The following shows a simplified version of the User Logon function.

 

Controller components:

Four annotations, @ Controller, @ Scope, @ Resource, and @ Autowired, are used. If the annotation is not injected, a null pointer exception is thrown at the place where the annotation is called, if no NULL pointer is thrown, the bean has been injected.

package com.siti.spring20160316;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;@Controller@Scope("prototype")public class UserAction {@Resourceprivate UserService userService;@Autowiredprivate Utils utils;public boolean login(String userName, String password){System.out.println("UserAction--login");if(utils.check(userName)){if(userService.login(userName, password)){return true;}}return false;}}

Service business logic layer

Here, we generally prefer to use interfaces during development. This is to make it clear that there is no interface in the form, so that readers can not clearly understand the process in the cloud.

The annotations used here include @ Service (marking the business logic layer), @ PostCustruct (marking method is equivalent to initMethod), and @ PreDestroy (marking method is equivalent to destroyMethod)

Package com. siti. spring20160316; import javax. annotation. postConstruct; import javax. annotation. preDestroy; import javax. annotation. resource; import org. springframework. stereotype. service;/***** @ ProjectName SpringBlob * @ ClassName UserService * @ Description generally, interfaces are used, and no interfaces are used here, it is easy for the reader to directly understand the call relationship * @ author wy * @ date 2016-3-16 **/@ Servicepublic class UserService {@ Resourceprivate UserDao userDao; public boolean login (String userName, String password) {System. out. println ("UserService -- login"); if (userDao. isExist (userName, password) {return true;} return false;} @ PostConstructpublic void init () {System. out. println ("UserService -- init") ;}@ PreDestroypublic void destroyMethod () {System. out. println ("UserService -- destroyMethod ");}}
DAO Layer

The main annotations used are @ Repository.

This is a persistent operation that simulates the parts that have not been added to the connected database. Sorry.

package com.siti.spring20160316;import org.springframework.stereotype.Repository;@Repositorypublic class UserDao {public boolean isExist(String userName, String password){System.out.println("UserDao--isExist");if("wy".equals(userName)){return true;}return false;}}

Test

The first output compares whether the two objects are the same. Readers can check whether several other objects are the same. Because the UserAction class marks @ Scope annotation and specifies its type as prototype, it should be different here, and the output is false

Package com. siti. spring20160316; import org. springframework. context. support. abstractApplicationContext; import org. springframework. context. support. classPathXmlApplicationContext; public class MainTest {public static void main (String [] args) {AbstractApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext20160316.xml"); UserAction action = (UserAction) context. getBean ("userAc Tion "); UserAction action2 = (UserAction) context. getBean ("userAction"); System. out. println ("whether the two objects are the same object:" + action. equals (action2); boolean bool = action. login ("wy", "******"); if (bool) {System. out. println ("Logon successful! ");} Else {System. out. println (" Logon Failed! ");} Context. registerShutdownHook ();}}

Output result

Custom Annotation

Here, I just wrote an annotation myself, but there is no way to use it without a parsing class. You can try to see if you can write your own processing class and share it with others.

Package com. siti. spring20160316; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Retention (RetentionPolicy. RUNTIME) // inject @ Target ({ElementType. FIELD, ElementType. METHOD}) // Where can I mark it? Here is the attribute and METHOD public @ interface MyAutowired {// parameter public String name () default "";}

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.