Use Intellijidea to create a MAVEN project for Spring IOC testing

Source: Internet
Author: User

Use Intellijidea to create a MAVEN project for the Spring IOC test IOC concept

Control inversion (inversion of controls, abbreviated to IOC) is a design principle in object-oriented programming that can be used to reduce the degree of coupling between computer code. The most common way is called Dependency injection (Dependency injection, short DI). By controlling the inversion, the object is created by an external entity that regulates all objects within the system, passing a reference to the object on which it depends. It can also be said that the dependency is injected into the object.

IOC and Di differences
    • IOC: Control inversion, object creation to spring configuration
    • DI: Dependency Injection, setting a value to a property inside a class
    • Relationship: Dependency injection cannot exist alone and needs to be performed on the IOC Foundation
Create a spring instance for IOC testing

We use Intellijidea to do this, first creating a MAVEN project (MAVEN provides download management for the jar package in Java, so we can use the download and import jar package, recommended). Open idea, select Create New Project , select Create Maven project in the pop-up window, set the JDK and click Next to proceed to the next step.

After setting up Grouid, Artifactid, and Version, follow the prompts to set up a MAVEN project.

We modify the Pom.xml settings to configure the jar packages that need to be added for download:

 <dependencies> <dependency> <groupId>org.springframework</groupId> & Lt;artifactid>spring-context</artifactid> <version>4.2.4.RELEASE</version> &LT;/DEP endency> <dependency> <groupId>org.springframework</groupId> &LT;ARTIFAC        Tid>spring-core</artifactid> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring -beans</artifactid> <version>4.2.4.RELEASE</version> </dependency> <de Pendency> <groupId>org.springframework</groupId> <artifactid>spring-expression& lt;/artifactid> <version>4.2.4.RELEASE</version> </dependency> <dependenc Y> <groUpid>junit</groupid> <artifactId>junit</artifactId> <version>4.12</ver sion> <scope>test</scope> </dependency> <dependency> <gr Oupid>junit</groupid> <artifactId>junit</artifactId> <version>4.12</ve Rsion> </dependency> </dependencies>

When we modify the Pom.xml file, idea will prompt us to import, we can click on it Import Change , and of course set up Auto-Import auto-import:

We src/main/java create a new package under the package: cn.itcast.ioc and create a new User.java under the package:

package cn.itcast.ioc;public class User {    public void add(){        System.out.println("add......");    }    //public static void main(String[] args) {        //原始做法        //User user = new User();        //user.add();    //}}

Create a new applicationcontext.xml configuration file under the Resources directory:

<?xml version="1.0" encoding="UTF-8"?><!-- scheme约束 --><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <!-- ioc 入门 -->    <bean id="user" class="cn.itcast.ioc.User"></bean></beans>

Then src/main/java create the test file Testioc.java, and try to output the IOC instance through the configuration file by loading the bean, by handing it to spring to create the object:

package cn.itcast.ioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestIOC {    @Test    public void testUser(){        //1.加载 spring 配置文件,根据创建对象        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        //2.得到配置创建的对象        User user = (User) context.getBean("user");        user.add();    }}

Run Testioc.java, if the console can output the Add () method, then the test succeeds.

Injecting properties through a configuration file

Description: When creating an object, set a value to the property inside the class.

In spring we generally use the set method to inject.

Give me a chestnut:

src/main/java/under Create Userservice.java:

package cn.itcast.ioc;public class UserService {    //1 定义 user 类型    private User user;    //2 生成set 方法    public void setUser(User user) {        this.user = user;    }    public void add(){        System.out.println("service....");        user.add();    }}

To modify the Applicationcontext.xml file:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 注入对象类型 -->    <!-- 配置 service 和 user 对象 -->    <bean id="user" class="cn.itcast.ioc.User"></bean>    <bean id="userService" class="cn.itcast.ioc.UserService">        <!-- 注入 user 对象                name 属性值, service 类里面的属性名称                ref 属性, 配置bean 标签中 id 值       -->        <property name="user" ref="user"></property>    </bean></beans>

Modify Testioc.java:

package cn.itcast.ioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestIOC {    @Test    public void testUser(){        //1.加载 spring 配置文件,根据创建对象        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        //2.得到配置创建的对象        UserService userService = (UserService) context.getBean("userService");        userService.add();    }}

Successfully outputs the Add () method and injected properties of the UserService class in the console:

Creating an IOC instance with annotations

The above example is the ability to create objects by configuring an XML file, and spring provides another way to do this: annotations.

Introduction to Annotations
    • Special tags inside the code, using annotations to complete the function
    • Annotation notation @ annotation Name (property name = attribute value)
    • Annotations are used above the class, above and above the properties of the method
Create four annotations of an object
    • @Component
    • @Controller
    • @Service
    • @Repository

Mainly through the Component derivative of the other three in the Web layer, the business layer, the persistence layer annotations, mainly for the subsequent enhancement. But for me, these four annotation functions are the same now, all created objects.

We reconfigure the Applicationcontext.xml file, introduce new constraints, and turn on annotation scanning:

<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->    <!-- 开启注解扫描        (1) 到包里面扫描类,方法,属性上面是否有注解    -->    <context:component-scan base-package="cn.itcast.ioc"></context:component-scan>    <!-- 扫描属性上面的注解 -->    <!--<context:annotation-config></context:annotation-config>--></beans>

To modify the User.java file:

package cn.itcast.ioc;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;@Service(value = "user")  //相当于<bean id="user" class=""/>@Scope(value = "prototype") //多实例public class User {    public void add(){        System.out.println("add........");    }}

Modify Testioc.java:

package cn.itcast.ioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestIOC {    @Test    public void testUser(){        //1.加载 spring 配置文件,根据创建对象        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        //2.得到配置创建的对象,这里的getBean()方法中的 user 为User类通过注解的 value 值。        User user = (User) context.getBean("user");        user.add();    }}

Console successfully entered the user class's Add () method:

Injecting attributes with annotations

Similarly, we can inject attributes by using annotations.

There are two ways we can use the latter one by using @Autowired (auto-injection) or @Resource (name= "value") (Name property value: annotation to create object value).

Note: The set method is not required to use annotations.

Or raise a chestnut:

src/main/java/under Create the package and Userdao.java and Userservice.java.

Userdao.java:

package cn.itcast.anno;import org.springframework.stereotype.Service;@Service(value = "userDao")public class UserDao {    public void add(){        System.out.println("dao.........");    }}

Userservice.java:

package cn.itcast.anno;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import javax.annotation.Resource;@Service(value = "userService")public class UserService {    //得到dao 对象    //定义 dao 类型    //方法一:在 dao属性上面使用注解,完成对象注入//    @Autowired//    private UserDao userDao;    //使用注解不需要set 方法        //方法二:    //name属性值: 注解创建 dao对象 value 值    @Resource(name = "userDao")    private UserDao userDao;    public void add(){        System.out.println("service.......");        userDao.add();    }}

Using the annotation configuration in the applicationcontext.xml above, create the Testanno.java:

package cn.itcast.anno;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestAnno {    @Test    public void TestService(){        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        UserService userService = (UserService) context.getBean("userService");        userService.add();    }}

To run Testanno.java, the console outputs the following information:

Summarize:
    • With the IOC container of the spring framework, we can give the object's creation to spring, reducing the coupling of the code.
    • With the spring Framework IOC container, you can manage it by configuring both XML files and annotations.
    • Learn the two ways to inject attributes: Configure XML files and annotations.
    • Create the object first, and then inject the property.

Use Intellijidea to create a MAVEN project for Spring IOC testing

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.