Spring learning summary (seven): assembly Bean based on annotations

1. Introduction to common annotations

      In Spring, although the use of XML configuration files can achieve the assembly of Beans, if the number of Beans in the application is large, the XML configuration files will be too bloated, which will bring certain difficulties to maintenance and upgrades. Java has provided Annotation (annotation) function since JDK 5.0, and Spring also provides comprehensive support for Annotation technology. A series of Annotations are defined in Spring. Next, we will introduce the commonly used annotations.

1. Annotations used to create objects

      The annotations used to create objects are equivalent to configuring <bean id="" class=""></bean> in bean.xml

      (1) @Component : Used to store the current class object in the spring container, and the value attribute is used to specify the id of the bean. When not written, the default value is the current class name, and the first letter is lowercase.

      (2) @Controller : usually acts on the control layer (Controller layer), used to identify the class of the control layer as a Bean in Spring, and its function is the same as @Component.

      (3) @Service : usually acts on the business layer (Service layer), used to identify the business layer class as a Bean in Spring, and its function is the same as @Component.

      (4) @Repository : Used to identify the class of the data access layer (DAO layer) as a Bean in Spring, and its function is the same as @Component.

      (5) Explanation about context:component-scan :

      1) Use the component-scan element of the context namespace to scan for annotations, and its base-package attribute is used to notify spring of the directories that need to be scanned. as follows:

   <context:component-scan base-package="com.yht.example4"></context:component-scan>

      2) If you need to scan multiple packages at the same time, there are two ways to achieve it:

      Suppose you want to scan three packages of controller, service and dao:

      Method 1: Use commas to separate multiple packages.

   <context:component-scan base-package="com.yht.example4.controller,com.yht.example4.service,com.yht.example4.dao"></context:component-scan>

      Method 2: Configure to scan the same parent directory of multiple packages.

   <context:component-scan base-package="com.yht.example4"></context:component-scan>

      3) Configure which packages to scan under a given package-scan only the controller package and service package:

     <!--  
        use-default-filters:设置为false,不使用默认的过滤规则。
        include-filter:设置哪些包要扫描
      -->
   <context:component-scan base-package="com.yht.example4" use-default-filters="false">
       <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
       <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
   </context:component-scan>

      4) Configure which packages are not scanned under a given package-do not scan the controller package

    <!--
       exclude-filter:设置哪些包不扫描
     -->
    <context:component-scan base-package="com.yht.example4" use-default-filters="false">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

      (6) Case: Simulating UserSerive to call UserDao-realized by annotation

      1) Configure the package for annotation scanning in xml.

   <context:component-scan base-package="com.yht.example4"></context:component-scan>

      2) Create UserService and IUserDao and its implementation class UserDaoImpl, and add annotations.

@Service
public class UserService {
    @Autowired
    private IUserDao userDao;
    public void execute(){
        System.out.println("service的execute()方法");
        userDao.findUser();
    }
}
public interface IUserDao {
    void findUser();
}

 

@Repository
public class UserDaoImpl implements IUserDao {
    @Override
    public void findUser() {
        System.out.println("UserImpl1 的findUser()");
    }
}

      3) Perform a test.     

@Test
    public void  testAnno(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean6.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.execute();
    }

      The execution results are as follows:

       

2. Annotations used to inject values

      The annotation used to inject the value is equivalent to the operation of injecting the value into the bean object in bean.xml, <property name="" value=""></property> or <property name="" ref=""></ property>

      (1) @Autowired : Used to annotate the attribute variables, attribute Set methods and constructors of the Bean, and cooperate with the corresponding annotation processor to complete the automatic configuration of the Bean. The assembly is performed according to the type of Bean by default. As in the example above.

      (2) @Qualifier : Used in conjunction with the @Autowired annotation, the default assembly by Bean type will be modified to assembly by the instance name of the Bean, and the instance name of the Bean is specified by the parameter of the @Qualifier annotation.

      In the above example, if there are multiple subclasses of IUserDao, @Autowired will not be able to determine which subclass to choose for injection, so @Autowired and @Qualifier need to be used together.

      When adding two dao implementation classes, the following error will be reported at this time:

      No qualifying bean of type 'com.yht.example4.dao.IUserDao' available: expected single matching bean but found 3: userDaoImpl,userImpl1,userImpl2。

      This problem can be solved by adding @Qualifier annotation to the userDao object in the service. as follows:

    @Autowired
    @Qualifier(value = "userImpl1")
    private IUserDao userDao;

      The execution results are as follows:

      (3) @Resource : It can be injected either by attribute or by type. @Resource is provided by Java, not Spring. Use as follows:

   @Resource(name = "userImpl2")
    private IUserDao userDao;

      The execution results are as follows:

 

      (4) @Value : Used to inject data of basic type and String type. Add a basic attribute to userService: name, use @Value to inject the value and output it.

    @Value("User Service")
    private String name;

      The results are as follows:

3. Annotation for changing the scope of action

      @Scope : Used to specify the scope of the bean, its attribute value specifies the value of the scope, commonly used values: singleton, prototype.

4. Used for life cycle related

      (1) @PreDestory : Used to specify the destruction method.

      (2) @PostConstruct : Used to specify the initialization method.

5. Other new notes

      (1) @Configuration : The annotated class is a configuration class.

      (2) @ComponentScan : Specify the package that Spring will scan when creating the container through annotations. The role of basePackages is the same, both are used to specify the packages to be scanned when creating a container. Equivalent to <context:component-scan base-package="com.day2"></context:component-scan> in XML

      (3) @Import : Import other configuration classes.

      (4) @Bean : Used to store the return value of the current method as a bean object in the spring's ioc container

Two, pure annotation development case-no configuration file

      Simulate a three-tier architecture: find users.

      The directory structure is as follows:

      1. The MySpringConfig class is used as the configuration class to replace the original xml file.

//作为配置类,代替xml
@Configuration
@ComponentScan("com.yht.example5")
public class MySpringConfig {
}

      2. UserController of the control layer

@Controller
public class UserController {
    @Autowired
    private IUserService userService;
    public void isExist(){
        System.out.println("controller层:判断用户是否存在");
        userService.findUser();
    }
}

      3. The IUserService and implementation classes of the service layer.

public interface IUserService {
    void findUser();
}
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;
    @Override
    public void findUser() {
        System.out.println("service层:查找用户");
        userDao.query();
    }
}

4. IUserdao and implementation class of dao layer

public interface IUserDao {
    void query();
}
@Repository
public class UserDaoImpl implements IUserDao {

    @Override
    public void query() {
        System.out.println("dao层:数据库查询");
    }
}

      4. Unit testing

    @Test
    public void  test(){
        ApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class);
        UserController userController = context.getBean("userController", UserController.class);
        userController.isExist();
    }

      The results are as follows:

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112784055