Automatic assembly of Bean

Preface


Today we will summarize the problem of bean assembly. A software needs to establish cooperation between classes with different functions in order to be assembled into a powerful system. Spring is a scheduler in it. The summary is: I know you need What, I provide you with what you need, and you only need an empty brain, focus on the business logic you want to complete, and leave the rest to me.

Have you been moved by Spring? For example, a computer contains many components. Does Cup know that it needs a hard disk? I don’t know, this requires a worker to assemble it together. What you get is a machine with all accessories, and spring is the assembler.

assembly


The act of creating a cooperative relationship between application objects is usually called wiring, which is also the essence of DI (dependency injection)

Three configuration methods:

  1. Display configuration in XML
  2. Display configuration in JAVA
  3. Implicit bean discovery mechanism and automatic assembly

Automated bean assembly

  • Component scanning: Spring will automatically discover beans created in the application context
  • Auto-wiring: Spring automatically meets the dependencies between beans
Example: (taken from "spring actual combat")


This small example is based on a CD player. If the CD player does not add a record, then it is useless, so the dependency here is that the CD player depends on the record to play.

1. Create a record

public interface CompactDisc {
    void play();
}

A coding philosophy worth thinking about: Define a record as an interface. It defines the operations that a CD player can perform on a record. He reduces the coupling between the arbitrary realization of the CD player and the CD itself to a minimum.

Second, the realization of the record

@Component
public class SgtPeppers implements CompactDisc {
    
    

    //beatles1967年发行的专辑
    private String title="Sgt.Perpper's Lonely Hearts Club Band";
    private String artist="The Beatles";

    public void play() {
        System.out.println("Playing "+title+" by "+artist);
    }

}

The difference between ps @Component, @Repository, @Service and @Controller

  • @Service is used to annotate business layer components
  • @Controller is used to annotate control layer components (such as action in struts)
  • @Repository is used to annotate data access components, namely DAO components
  • @Component refers to components in general. When components are not well classified, we can use this annotation for annotation.

They are all meta-annotations, used to annotate other annotations, and their role here: Annotated on a certain class, the class will be automatically registered as a BeanDefinition by the Spring container (when scanning the package, if there are the above four annotations, then Manage this class into the spring container)

Three, configure spring

Component scanning is not started by default. You need to display and configure Spring. There are two ways to configure, one is to use Java code to define Spring assembly rules, and the second is to use xml configuration files.

method one:

@Configuration
@ComponentScan
public class CDPlayerConfig {
    
    
}

Annotated with @Configuration, indicating that this class is a configuration class, and @ComponentScan will scan packages with the same configuration class by default

testing method:

//在测试开始的时候自动创建Spring的应用上下文
@RunWith(SpringJUnit4ClassRunner.class)
//会告诉他需要在CDPlayerConfig中加载配置。因为CDPlayerConfig包含了@ComponentScan,最终的应用上下文中应该包含CompactDisc bean
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
    
    
    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull(){
        assertNotNull(cd);
    }

}

Method 2:
Configure the package scanner in the xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    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-4.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!-- 配置包扫描器 -->
    <context:component-scan base-package="soundsystem"/>
</beans>

testing method:

第二种测试方法:(配置文件)

public class CDPlayerTest {
    
    
    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull(){
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
        context.start();
        cd=(CompactDisc) context.getBean("lonelyHeartsClub");
        assertNotNull(cd);
    }

}
to sum up


Today, I briefly learned some of the most basic applications of spring assembly. This is just the simplest example. When the business is complex, various other scenarios will appear, and the power of spring will slowly manifest.

Guess you like

Origin blog.csdn.net/cd18333612683/article/details/79021642