7.5Java EE - Bean assembly method

1. XML-based assembly

Two assembly methods based on XML

        The XML-based assembly is to read the information in the XML configuration file to complete dependency injection. The Spring container provides two XML-based assembly methods, property setter method injection and construction method injection. The two assembly methods are introduced respectively below.

a. Property setter method injection

Property setter method injection requires that a Bean must meet the following two requirements.        

(1) The Bean class must provide a default no-argument constructor.        

(2) The Bean class must provide corresponding setter methods for the properties that need to be injected.

b. Constructor injection

        When using constructor injection, in the configuration file, you need to use the sub-element <constructor-arg> of the <bean> element to define the parameters of the construction method. For example, you can use its value attribute (or sub-element) to set the value of the parameter.

2. Annotation-based assembly

Comparison of XML and Annotation Assembly 

        In Spring, the assembly of beans can be realized by using XML configuration files, but in actual development, if the number of beans is large, the XML configuration files will be too bloated, which will bring certain difficulties to later maintenance and upgrades. To solve this problem, Spring provides annotations, and Bean assembly can also be realized through annotations.

Spring's common annotations

annotation

describe

@Component

Specify an ordinary Bean, which can be used at any level.

@Controller

Specify a controller component bean to identify the class of the control layer as a bean in Spring,

Functionally equivalent to @Component.

@Service

Specify a business logic component bean to identify the class of the business logic layer as a bean in Spring,

Functionally equivalent to @Component.

@Repository

Specify a data access component bean to identify the class of the data access layer as a bean in Spring,

Functionally equivalent to @Component.

@Scope

Specifies the scope of the Bean instance.

@Value

Specifies the injected value of the Bean instance.

annotation

describe

@Autowired

Specifies the objects to autowire.

@Resource

Specifies the object to inject.

@Qualifier

Specifies the object name to be autowired, usually used in conjunction with @Autowired.

@PostConstruct

Specifies the method to invoke after the Bean instance has completed initialization.

@PreDestroy

Specifies the method to call before the Bean instance is destroyed.

 The following example demonstrates how to use annotations to assemble beans. The specific implementation steps are as follows.

1. Import dependencies: Import the spring-aop-5.2.8.RELEASE.jar dependency package in the pom.xml file of project chapter07, and the import code is as follows.

<dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>5.2.8.RELEASE</version>
 </dependency>

2. XML configuration file: Create applicationContext.xml, introduce Context constraints in this file and start the automatic scanning function of Bean.

<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">
    <context:component-scan base-package="com.mac" />
</beans>

3. Define the entity class: create a new entity package, and create a User entity class under the entity package.

@Component("user")
@Scope("singleton")
public class User {
    @Value("1")
    private int id;
    @Value("张三")
    private String name;
    @Value("123")
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String toString(){
        return "id="+id+",name="+name+",password="+password;
    }
}

4. Define the dao layer: Create the UserDao interface as the data access layer interface, and declare the save() method in the UserDao interface to query the object information of the User entity. 

package com.mac.dao;
public interface UserDao {
    public void save();
}

5. Implement the dao layer: Create UserDaoImpl as the implementation class of UserDao, and implement the save() method in the UserDao interface in the UserDaoImpl class.

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    public void save(){
        ApplicationContext applicationContext=new 
              ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User) applicationContext.getBean("user");
        System.out.println(user);
        System.out.println("执行UserDaoImpl.save()");
    }
}

6. Define the service layer: Create the UserService interface as the business logic layer interface, and define the save() method in the UserService interface.

package com.mac.service;
public interface UserService {
    public void save();
}

7. Implement the service layer: Create UserServiceImpl as the implementation class of UserService, and implement the save() method in the UserService interface in the UserServiceImpl class.

@Service("userService")
public class UserServiceImpl implements UserService {
        //使用@Resource注解注入UserDao
        @Resource(name="userDao")
        private UserDao userDao;
        public void save(){
            this.userDao.save();
            System.out.println("执行UserServiceImpl.save()");
        }
}

8. Define the controller layer: Create the UserController class as the control layer.

@Controller
public class UserController {
    //使用@Resource注解注入UserService
    @Resource(name="userService")
    private UserService userService;
    public void save(){
        this.userService.save();
        System.out.println("执行UserController.save()");
    }
}

9. Define the test class: Create the test class AnnotationTest, write the test code in this class, load the configuration file through the Spring container and obtain the UserController instance, and then call the save() method in the instance.

public class AnnotationTest {
    public static void main(String[] args){
        ApplicationContext applicationContext=new 
             ClassPathXmlApplicationContext("applicationContext.xml");
        UserController usercontroller=(UserController) 
             applicationContext.getBean("userController");
        usercontroller.save();
    }
}

10. View the running results: Start the AnnotationTest class in IDEA, and the console will output the results.

3. Automatic assembly

Spring's <bean> element contains an autowire attribute, which can realize automatic assembly of beans by setting the value of the autowire attribute.

The value of the autowire attribute

attribute value

describe

default (default value)

Determined by the value of the default-autowire attribute of the superior element <beans> of <bean>.

byName

Autowired based on the value of the id attribute of the <bean> element.

byType

Autowire according to the data type (Type) of the <bean> element, if a Bean's data type,

Compatible with the data type in another bean, it is automatically wired.

constructor

According to the data type of the constructor parameter, the automatic assembly of the byType mode is performed.

no

By default, no autowiring is used, and bean dependencies must be defined via <ref> elements or ref attributes.

 

Guess you like

Origin blog.csdn.net/W_Fe5/article/details/131803944
Recommended