Spring entry (1), spring entry (

Source: Internet
Author: User

Spring entry (1), spring entry (

This section describes how to set up the spring environment. The spring environment can be divided into the java environment and the java Web environment. In the javaWeb environment, springMVC is usually used in combination, in the java project, you only need to import the spring package into the project. Generally, beginners will import all the packages, and then they can get the applicationContext and pass the class Instantiation to spring management, then obtain the instance of the class from the spring container.

In spring, there are two concepts: Control inversion (Ioc) and dependency injection (DI). Ioc and DI are the core concepts of spring and a new programming concept.

Control inversion (Ioc)

Control inversion, as its name implies, is a change in control. Before we get in touch with spring, we need to use a class instance and use the new method to generate an object, the initiative in this process is in programs written by programmers themselves. However, after spring is used, the creation of instances is not manually implemented by programmers, but by spring containers, the control is reversed, that is, the initiative is handed over to the IOC container of spring.

Dependency injection (DI)

A class includes attributes and Methods. After creating an instance object or creating an instance object, you must initialize the member variable (attribute ), before spring, the member variables can be initialized through the constructor or setXXX method. After spring appears, the instance creation is handed over to the spring IOC container, the initialization of member variables also depends on the IOC container, which injects the value of member variables.

The IOC and DI concepts are introduced above. It can be concluded that IOC and DI are actually doing one thing, that is, creating instance objects in the spring IOC container, all Object Instantiation is handed over to the spring container. in the program, you do not have to manually instantiate variables using the new method.

Spring provides two different ways to configure spring. One is the configuration file (XML), and the other is based on Annotation (Annotation ). The following two methods are used to describe IOC and DI:

Before proceeding, you must understand how to obtain the spring container, that is, ApplicationContext, in the java project.

ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:applications.xml");

There are three ways to obtain ApplicationContext: ClassPathXmlApplicationContext, ClassPathApplicationContext is the subclass of ApplicationContext, and cpac is the IOC container of spring, through its getBean () method to obtain the initialized instances in the container.
Configuration file (XML)

Suppose we have student)

Package com.cn. study. day1; public class Student {private String id; private String name; private String age; public String getId () {return id;} public void setId (String id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getAge () {return age;} public void setAge (String age) {this. age = age ;}@ Override public Strin G toString () {return "Student [id =" + id + ", name =" + name + ", age =" + age + "]";} // a constructor with parameters must provide a public Student (String id, String name) {this. id = id; this. name = name;} // public Student () {} public void init () {System. out. println ("I'm initializing! ");} Public void destroy () {System. out. println (" I'm about to be destroyed ,. Goodbye! ");}}

This class has three attributes: id, name, and age. The configuration file is used in the spring configuration file,

<Bean id = "student" class = "com.cn. study. day1.Student "> <property name =" id "value =" 1 "> </property> <property name =" name "value =" test "> </property> <property name = "age" value = "23"> </property> </bean>

Configure the <bean> label in the spring configuration file. The id attribute must be unique in the configuration file. The class attribute specifies the permission class Name of the class. The <property> label is shown below, specify the three attributes of Student and the attribute value. The test result is as follows,

Student [id = 1, name = test, age = 23]

Here we can see that the configuration value is output. This method uses the property injection method, which requires the setXXX method, and another method, which is injected by the constructor,

<! -- Constructor injection --> <bean id = "student2" class = "com.cn. study. day1.Student "init-method =" init "destroy-method =" destroy "> <constructor-arg name =" id "value =" 2 "> </constructor-arg> <constructor -arg name = "name" value = "test2"> </constructor-arg> </bean>

Since it is injected through the constructor method, this constructor must be available in the Student class. The preceding Student class already has a constructor with parameters, we know that after the construction method with parameters is customized, the system will not provide the construction without parameters by default. We must also add the construction without parameters. The test result is as follows,

Student [id=2, name=test2, age=null]

Because we only inject the id and name attributes, We can print them out here. age is null by default because it is not assigned a value and its type is String.

The preceding configuration file is used to configure the injection method based on attributes and constructor methods. This example is relatively simple. The following describes a complicated example, in programs, we often use the thought of layered and interface-oriented programming,

DAO Interface

Package com.cn. study. day1.inter; public interface dbDAO {// The save interface of a simple dao layer public void save (String str );}

Service Interface

Package com.cn. study. day1.inter; public interface ServiceInter {/*** method of saving the service layer */public void save (String str );}

DAO implementation class

Package com.cn. study. day1.inter. impl; import com.cn. study. day1.inter. dbDAO; public class DbDAOImpl implements dbDAO {@ Override public void save (String str) {// TODO Auto-generated method stub System. out. println (str + ", I will insert data! Will you? ");}}

Service implementation class

Package com.cn. study. day1.inter. impl; import com.cn. study. day1.inter. serviceInter; import com.cn. study. day1.inter. dbDAO; public class ServiceImpl implements ServiceInter {// DAO interface object private dbDAO; // setXXX method public void setDbDAO (dbDAO) {this. dbDAO = dbDAO ;}@ Override public void save (String str) {// TODO Auto-generated method stub if (str! = Null &&! "". Equals (str) {dbDAO. save (str); System. out. println ("the DAO layer method has been executed. I am a service layer method! ");}}}

There is a DAO-layer interface object in the service implementation class. Let's see how this class is injected according to the attribute,

<! -- The following is an example of complex property injection --> <bean id = "dbDao" class = "com.cn. study. day1.inter. impl. DbDAOImpl"> </bean> <! -- The following class has a dbDAO attribute that requires property injection. A set method must be provided --> <bean id = "service" class = "com.cn. study. day1.inter. impl. serviceImpl "> <property name =" dbDAO "ref =" dbDao "> </property> </bean>

First, configure the bean at the DAO layer. The class attribute must be configured with its implementation class, and then configure the service implementation class. ServiceImpl has a dbDAO type attribute, use the ref attribute to reference the bean above. The test results are as follows,

I'm a test method. I will perform the data insertion Operation! Will you? After running the DAO layer method, I am the service layer method!


The ref attribute can reference the bean in the spring configuration file and use the id value.

Through the above introduction, we can know that this method can be easily configured by using the configuration file. However, when there are many classes to be configured and there are many dependencies, this method will be cumbersome, the other method is useful.

Annotation (Annotation)

Spring provides four Annotations: @ Component, @ Repository, @ Controller, and @ Service. In fact, you can only use @ Component to do this, @ Repository, @ Controller, and @ Service are only set for different layers, which can be more obvious. @ Repository corresponds to the DAO layer, @ Controller corresponds to the control layer, and @ Service corresponds to the Service layer, the three annotations can be clearly layered to make the system easy to understand, or only @ Component can be used.

If annotations are used, you need to enable the automatic scanning mechanism of components. To enable the automatic scanning mechanism of components in the spring configuration file, you need to support the context namespace. The following is an example of the configuration file,

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans -3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! -- Spring Automatic Detection --> <context: component-scan base-package = "com.cn. study. day1"/> </beans>

Add the support for the context namespace in the header of the spring configuration file, and then use the <context: component-scan base-package = ""> label to enable component scanning, the base-package attribute specifies the base package to be scanned. This package and its sub-packages will be scanned. After the component scan is enabled, automatic injection is required. For example, <context: annotation-config/> is required on the Internet. In fact, the preceding component scan already contains the function of this label, to do this, you do not need to configure this label. Automatic injection is injected Based on the type (byType) by default, and the value of the bean id is injected according to the name (byName, and constructor ). The @ Aotuwired annotation is required for automatic injection. This annotation can be placed on the property or the setXXX method. If it is placed on the property, the setXXX method can be omitted. The following is an example.

Package com.cn. study. day1; import org. springframework. stereotype. component; @ Component ("su") public class StudentAnnotation {public void print () {System. out. println ("I Am a class generated using annotation! ");}}

Use the @ Component Annotation on the class and specify the Instance name su. If not specified, the first letter of the class name is lowercase by default, that is, studentAnnotation.

The following is an example of automatic scanning and automatic injection,

Package com.cn. study. day1.inter. impl; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import com.cn. study. day1.inter. serviceInter; import com.cn. study. day1.inter. dbDAO; @ Servicepublic class ServiceImpl implements ServiceInter {// DAO interface object @ Autowired private dbDAO; // setXXX method public void setDbDAO (dbDAO) {this. dbDAO = dbDAO;} @ Over Ride public void save (String str) {// TODO Auto-generated method stub if (str! = Null &&! "". Equals (str) {dbDAO. save (str); System. out. println ("the DAO layer method has been executed. I am a service layer method! ");}}}

The @ Service annotation is used on the class, and the @ Autowired annotation is used on the property. In this case, the setDbDAO () method is optional. @ Autowired annotation is used to omit the setXXX method. @ Autowired annotation uses injection by type by default. If multiple instances of the same type exist, automatic injection will fail here. In order to be correctly injected, introduce another annotation @ Qualifier (value = ""). The value Attribute of this annotation can specify the id value of a bean for automatic injection.
@ Qualifier can be used in attributes or setXXX methods.

In summary, dependency injection is introduced through configuration files and annotations.

Thank you for your attention.

 

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.