View on GitHub

heartCraft.github.io

一朵野花,随风摆荡

Spring学习总结记录

控制反转(IOC:Inversion of Control)

控制反转实为依赖注入(DI:dependency injection),依赖查找(DL:depandency lookup)

实现方式

JavaConfig

@Configuration
public class Config {
    @Bean
    public Patient patient() {
        return new Patient("stomachache!");
    }

    @Bean
    public Doctor doctor() {
        Doctor docter = new Doctor();
        docter.setPatient(patient());
        return docter;
    }
    // 相同的效果,不同的实现(在获取Docter实体时,会自动装配patient对象到此参数)
    /*@Bean
    public Doctor docter(Patient patient) {
        Doctor docter = new Doctor();
        docter.setPatient(patient);
        return docter;
    }*/
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <bean id="patient" class="com.xml.Patient">
        <!--替代方案:c命名空间-->
        <constructor-arg value="stomachache!"/>
    </bean>

    <bean id="doctor" class="com.xml.Doctor">
        <!--替代方案:p命名空间-->
        <property name="patient" ref="patient"/>
    </bean>

    <!--进阶:如何装配集合,util命名空间-->

    <!--引用javaConfig-->
    <!--<bean class=""/>-->

    <!--引用其他bean xml文件-->
    <!--<import resource=""/>-->
</beans>

基于JavaConfig或XML的自动化扫描与装配

@Component
public class Doctor {
    private Patient patient;

    public Patient getPatient() {
        return patient;
    }

    @Autowired
    public void setPatient(Patient patient) {
        this.patient = patient;
    }
}
@Component
public class Patient {
    // 症状
    private String symptom;

    @Autowired
    public Patient(String symptom) {
        this.symptom = symptom;
    }

    public String getSymptom() {
        return symptom;
    }

    public void setSymptom(String symptom) {
        this.symptom = symptom;
    }
}

打开扫描功能方式:

核心:Spring容器