Spring Learning (six) bean Detailed assembly of notes assembled by Bean [] [] basic configuration

Notes assembled by Bean

1. Introduction

Advantage

1. XML configuration can be reduced, when the number of configuration items, XML configuration too much can cause a bloated project difficult to maintain

2. The more powerful, both to achieve XML functions, but also provides the ability to automatically assembled using automatic assembly, the program ape decision needs to do less, and more conducive to the development of the program, which is "agreement over configuration " of development principles

IOC found two ways of Bean

Component scans : resources defined by way let Spring IoC container scanning corresponding packet, thereby coming bean assembly.

Automatic assembly : By definition of annotation, such that some of the dependencies may be accomplished by annotation.

2, using assembly Bean @Compoent

We created the Student class change it before:

package pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "student1")
public class Student {

    @Value("1")
    int id;
    @Value("student_name_1")
    String name;

    // getter and setter
}

 explain:

@Component notes:

  Spring IoC represents the class would be scanned as a bean instance, the value of which represent this class id attributes in Spring, which is equivalent to the Bean id defined in XML: <bean id = "student1" class = " pojo.Student "/>, can be abbreviated as @Component (" student1 "), or even directly written @Component, for not writing, Spring IoC container will default to the class name to name as the id, but the first letter lowercase, configuration into the container.

@Value notes:

  Was filled with values, with the value written in XML attribute is the same.

    Well, so we declare that we want to create a Bean, just wrote this sentence in XML:

<bean name="student1" class="pojo.Student">
    <property name="id" value="1" />
    <property name="name" value="student_name_1"/>
</bean>

   But now we declare the class, and can not perform any test, because the Spring IoC does not know the existence of this Bean, this time we can use a StudentConfig class to tell Spring IoC:

package pojo;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class StudentConfig {
}

This class is very simple, without any logic, but two points should be noted:

1, in the same class and the Student class package name

2, @ ComponentScan notes:

Representatives scanning, scanning is the default path of the current package, with @Component scan all annotated POJO.

  As a result, we can define the class that implements good through Spring IoC container Spring --AnnotationConfigApplicationContext to generate the IoC container:

ApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);
Student student = (Student) context.getBean("student1", Student.class);
student.printInformation();

  Here you can see the AnnotationConfigApplicationContext used to initialize class Spring IoC container, it is StudentConfig configuration item class, so will Spring IoC to resolve resource corresponding to the configuration according to annotation, to generate the IoC container.

Obvious disadvantages:

  • For @ComponentScan notes, it just scans Java class where the package, but more often we hope that we can scan a specified class
  • The above example is just a simple injection value, the test was found, the object can not be injected through the annotation @Value

@Component notes there are two configuration items:

basePackages: It is a base and a package of two words, while the package or use the plural, meaning that it can be configured to package an array of Java, Spring will configure the scan based on its corresponding package and sub-packages will be configured Bean assembly come

basePackageClasses: It consists of base, package, and class composed of three words, the use of complex, meaning that it can configure a plurality of classes, Spring based configuration where the bags, conducted Bean scanning assembly configured for the corresponding packet and sub-packet

Let's try to write before reconstruction StudentConfig class to verify the above two configuration items:

package pojo;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "pojo")
public class StudentConfig {
}

//  —————————————————— 【 宇宙超级无敌分割线】—————————————————— 
package pojo;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackageClasses = pojo.Student.class)
public class StudentConfig {
}

For basePackages [] and [] basePackageClasses choice question:

  [BasePackages] readability would be better, so the project will give priority to use it, but requires a lot of remodeling project, try not to use [basePackages], because reconstruction often need to modify the package name repeatedly configuration, and IDE will not give you any hints, and use [] basePackageClasses error messages.

3, automatic assembly - @ Autowired

Definition: the Spring found their corresponding Bean, automatically assembling work way ( to find the type )

Examples of analysis:

1. create a StudentService interface under Package [service]:

package service;

public interface StudentService {
    public void printStudentInfo();
}

PS: Use Interface Spring is the recommended way, so you can be more flexible, and can be defined to achieve separation

2. The above interface to create a StudentServiceImp implementation class:

@Component ( "studentService") // indicates IoC this class scanned into a bean instance (abbreviated herein, the time equivalent to the XML configuration id in parentheses) 
public  class StudentServiceImp the implements StudentService { 

    @Autowired // the Spring and he discovered bean assembly 
    Private student student = null ; 

    public  void printStudentlnfo () { 
        System.out.println ( "student id is:" + student.getName ()); 
        System.out.println ( "student name is:" + student. getName ()); 
    } 
}

3. Write a test class:

// Step: Review StudentConfig class Spring IoC tell it where to scan: 
Package POJO; 

Import org.springframework.context.annotation.ComponentScan; 

@ComponentScan (basePackages = { "POJO", "-Service" })
 public  class {StudentConfig 
} 

// or may be declared in the XML file where to do the scan 
<context: scan-base- Component Package = "POJO" /> 
<context: scan-base- Component Package = "-Service" /> // first two-step: write test classes: Package Penalty for the test; Import org.springframework.context.ApplicationContext;
 Import




 org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.StudentConfig;
import service.StudentService;
import service.StudentServiceImp;

public class TestSpring {

    public static void main(String[] args) {
        // 通过注解的方式初始化 Spring IoC 容器
        ApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);
        StudentService studentService = context.getBean("studentService", StudentServiceImp.class);
        studentService.printStudentInfo();
    }
}

summary:

@Autowired annotation represents the Spring IoC after positioning all the Bean, and then find the resources depending on the type, then injected.

Process: definition of Bean - "Initialization Bean (Scan) -" Bean needed to meet the requirements from the search Spring IoC container according to the attributes - 'meet the requirements of the injection

Question: IoC container might be looking for failure, then will throw an exception (by default, Spring IoC container would think that we must find the corresponding Bean to inject into this field, but sometimes not necessarily need, such as logging)

Resolution: changed by using the configuration required, such @Autowired (required = false), this property not being given IOC container may be controlled not find Bean.

PS: @Autowired annotation can be configured not only on the properties, the method also allows configuration, Bean common setter method also can use it to complete the injection, in short, everything you need to find Bean Spring IoC local resources can be used

Guess you like

Origin www.cnblogs.com/riches/p/11521428.html