Spring Framework Tutorial (3): IOC annotation-based Bean management

1. Annotation overview

  What is an annotation:

  • Format : Annotation is a code special mark, the format is @Annotation name (attribute name=attribute value, attribute name=attribute value...).
  • Role : Act on classes, methods, and attributes.
  • Purpose : to simplify the xml configuration.

  Spring provides annotations for creating objects in bean management:

  • @Component
  • @Service
  • @Controller
  • @Repository

  Spring provides annotations for injecting properties in bean management:

  • @AutoWired injects attributes based on type
  • @Qualifier injects attributes based on the attribute name
  • @Resource can inject attributes based on name or type
  • @Value injects basic types or built-in reference classes (such as String)

Two, create an object

  In order to distinguish it from what we have learned before, we create a new project spring5_demo1, which will be demonstrated in the new project starting from this chapter.

(1) The first step: import the required jar package

  Create the directory lib under the project, copy all the jar packages under lib in the previous project, and find a new jar under the libs folder under the spring-5.2.6.RELEASE-dist folder on our computer The package spring-aop-5.2.6.RELEASE is also put into the lib.

  Import jar resources:

  • In the IDEA project, click File-Project Structure-Module-Dependency, and then click the + sign.
  • Find the location of the 5 jar packages you just copied in, select them, and import them.
  • Click Apply and then click OK.

(2) Turn on component scanning

  • Create a bean.xml file under src.
  • Introduce the context name space:
	<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">//添加
  • Turn on component scanning and configure it in the beans tag of xml:
	<!--开启组件扫描-->
    <context:component-scan base-package="com.wang"></context:component-scan>

(3) Use create object annotation

  • Create the package service under com.wang.
  • Then create the class UserService under the service, and add the corresponding annotations:
	package com.wang.service;
	import org.springframework.stereotype.Service;
	
	//相当于xml中<bean id="userService" class=...></bean>
	//注解的value属性可以省略不写,默认对象名就是首字母小写后的类名
	//Component、Service、Controller、Repository四个注解使用任意一个就行
	@Service(value="userService")
	public class UserSerivce {
    
    
	
	    public void add(){
    
    
	        System.out.println("service add...");
	    }
	}

(4) Test

  • Create package test under com.wang.
  • Create the TestDemo class under test and execute the method:
	package com.wang.test;
	import com.wang.service.UserSerivce;
	import org.junit.jupiter.api.Test;
	import org.springframework.context.ApplicationContext;
	import org.springframework.context.support.ClassPathXmlApplicationContext;
	
	public class TestDemo {
    
    
	    @Test
	    public void testUserService(){
    
    
	        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
	        UserSerivce userSerivce = context.getBean("userService", UserSerivce.class);
	        System.out.println(userSerivce);
	        userSerivce.add();
	    }
	}

Insert picture description here

Three, component scan configuration

  Which scans and which do not scan. Just read the following two examples:

	<!--配置组件扫描示例1
    use-default-filters="false"表示使用自己配置的filter过滤器
    到com.wang中只扫描用@Controller注解的类-->
    <context:component-scan base-package="com.wang" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
 	<!--配置组件扫描示例2
    没有use-default-filters属性,表示使用默认配置的filter过滤器
    到com.wang中扫描所有内容,除了用@Controller注解的类-->
    <context:component-scan base-package="com.wang">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

Four, attribute annotation

  As mentioned earlier, there are three commonly used annotations for injected properties:

  • @AutoWired injects attributes based on type
  • @Qualifier injects attributes based on the attribute name
  • @Resource can inject attributes based on name or type
  • @Value injects basic types or built-in reference classes (such as String)

  We first create a dao package under com.wang.

(1)@AutoWired

  • Create a UserDao interface and the corresponding implementation class UserDaoImpl under dao, as follows:
	package com.wang.dao;
	public interface UserDao {
    
    
	    void add();
	}
	
	@Repository//注意,注解写在实现类上而不是接口上
	public class UserDaoImpl implements UserDao {
    
    
	    @Override
	    public void add() {
    
    
	        System.out.println("dao add...");
	    }
	}
  • Modify the UserService class as follows:
	package com.wang.service;
	
	import com.wang.dao.UserDao;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Service;
	
	@Service
	public class UserSerivce {
    
    
	    @Autowired //根据类型注入
	    private UserDao userDao;
	
	    public void add(){
    
    
	        System.out.println("service add...");
	        userDao.add();
	    }
	}
  • Test it, the test code has not changed:
	@Test
    public void testUserService(){
    
    
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        UserSerivce userSerivce = context.getBean("userService", UserSerivce.class);

        System.out.println(userSerivce);
        userSerivce.add();
    }

Insert picture description here

(2)@Qualifier

  To be used with @AutoWired.

	@Autowired //根据类型注入
    @Qualifier(value="userDaoImpl") //根据名称注入,如果同类型的有多个,可以定位到一个
    private UserDao userDao;

(3)@Resource

	@Resource//根据类型进行注入
    private UserDao userDao;
	@Resource(name="userDaoImpl)//根据名称进行注入
    private UserDao userDao;

(4)@Value

	@Value(value="abc")
    private String uname;

Five, pure annotation development

  It is not necessary to use or even delete the xml configuration file.

(1) Create a configuration class

  The config package is created under com.wang to store the configuration class SpringConfig (instead of the xml file):

	package com.wang.config;
	import org.springframework.context.annotation.ComponentScan;
	import org.springframework.context.annotation.Configuration;
	
	@Configuration //作为配置类,替代xml文件
	@ComponentScan(basePackages = {
    
    "com.wang"}) //组件扫描配置
	public class SpringConfig {
    
    
	}

(2) Write test class (different from before)

	@Test
    public void testUserService(){
    
    
        ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
        UserSerivce userSerivce = context.getBean("userService", UserSerivce.class);

        System.out.println(userSerivce);
        userSerivce.add();
    }

  The rest is still business as usual.

Guess you like

Origin blog.csdn.net/Tracycoder/article/details/112613341