Spring IoC — 基于XML的配置

简介: 原文:Spring IoC — 基于XML的配置1、属性注入 注意点: 1)如果类中显示定义了一个带参的构造函数,则一定还要显示提供一个无参构造函数,否则使用属性注入时将抛出异常。 2)JavaBean关于属性命名的特殊规范。
原文: Spring IoC — 基于XML的配置

1、属性注入

注意点:
1)如果类中显示定义了一个带参的构造函数,则一定还要显示提供一个无参构造函数,否则使用属性注入时将抛出异常。
2)JavaBean关于属性命名的特殊规范。Spring只会检查Bean中是否有对应的Setter方法,至于Bean中是否有对应的属性变量则不做要求。如maxSpeed对应setMaxSpeed(),brand对应setBrand()。
所以<property>元素的属性变量名应满足:xxx的属性对应setXxx()方法。变量的前两个字母要么全部大写,要么全部小写。
 
Car类:
package com.ioc.ch4_3_1;
/**
 * Created by gao on 16-3-25.
 */
public class Car {
    private int maxSpeed;
    public String brand;
    private double price;
    public Car() {
    }
    public Car(int maxSpeed, String brand, double price) {
        this.maxSpeed = maxSpeed;
        this.brand = brand;
        this.price = price;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getMaxSpeed() {
        return maxSpeed;
    }
    public String getBrand() {
        return brand;
    }
    public double getPrice() {
        return price;
    }
    public String toString() {
        return "brand:" + brand + "/maxSpeed:" + maxSpeed + "/price:" + price;
    }
}

beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="car" class="com.ioc.ch4_3_1.Car">
        <property name="maxSpeed"><value>300</value></property>
        <property name="brand"><value>奥迪</value></property>
        <property name="price"><value>150000.00</value></property>
    </bean>
</beans>

测试类:

package com.ioc.ch4_3_1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by gao on 16-3-25.
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com\\ioc\\ch4_3_1\\beans.xml");
        Car car = (Car) ctx.getBean("car");
        System.out.println(car.toString());
    }
}
输出结果:
brand:奥迪/maxSpeed:300/price:150000.0
 
2、构造函数注入
注意点:循环依赖问题。Spring容器能顺利实例化以构造函数注入方式配置的Bean有一个前提是:Bean构造函数入参引用的对象必须已经准备就绪。如果两个Bean都采用构造函数注入,而且都通过构造函数入参引用对方,则会发生循环依赖问题。这时可以将构造函数注入方式调整为属性注入方式。
Car类:
package com.ioc.ch4_3_2;
/**
 * Created by gao on 16-3-25.
 */
public class Car {
    private int maxSpeed;
    public String brand;
    private double price;
    private String corp;
    public Car() {
    }
    public Car(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }
    public Car(int maxSpeed, String brand, double price) {
        this.maxSpeed = maxSpeed;
        this.brand = brand;
        this.price = price;
    }
    public Car(String brand, String corp, int maxSpeed) {
        this.brand = brand;
        this.corp = corp;
        this.maxSpeed = maxSpeed;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getCorp() {
        return corp;
    }
    public void setCorp(String corp) {
        this.corp = corp;
    }
    public int getMaxSpeed() {
        return maxSpeed;
    }
    public String getBrand() {
        return brand;
    }
    public double getPrice() {
        return price;
    }
    public String toString() {
        return "brand:" + brand + "\tmaxSpeed:" + maxSpeed + "\tprice:" + price + "\tcorp:" + corp;
    }
}

Boss类:

package com.ioc.ch4_3_2;
public class Boss {
    private String name;
    private Car car;
    private Office office;
    public Boss(String name, Car car, Office office) {
        this.name = name;
        this.car = car;
        this.office = office;
    }
    public Boss(String name, Car car) {
        this.name = name;
        this.car = car;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String toString(){
        return "name:"+name+"\tcar:"+car.getBrand()+"\toffice:"+office;
    }
}

Office类:

package com.ioc.ch4_3_2;
public class Office {
   
}

beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!--构造函数注入:type -->
    <bean id="car1" class="com.ioc.ch4_3_2.Car">
        <constructor-arg type="java.lang.String">
            <value>car1_甲壳虫</value>
        </constructor-arg>
        <constructor-arg type="double">
            <value>300000.0</value>
        </constructor-arg>
    </bean>
    <!--构造函数注入:index-->
    <bean id="car2" class="com.ioc.ch4_3_2.Car">
        <constructor-arg index="0" value="300"/>
        <constructor-arg index="1" value="car2_宝马"/>
        <constructor-arg index="2" value="200000.0"/>
    </bean>
    <!--构造函数注入:type&index -->
    <bean id="car3" class="com.ioc.ch4_3_2.Car">
        <constructor-arg index="0" type="java.lang.String">
            <value>car3_红旗CA72</value>
        </constructor-arg>
        <constructor-arg index="1" type="java.lang.String">
            <value>中国一汽</value>
        </constructor-arg>
        <constructor-arg index="2" type="int">
            <value>200</value>
        </constructor-arg>
    </bean>
    <!--构造函数注入:自动识别入参类型 -->
    <bean id="boss1" class="com.ioc.ch4_3_2.Boss">
        <constructor-arg>
            <value>John</value>
        </constructor-arg>
        <constructor-arg>
            <ref bean="car1" />
        </constructor-arg>
        <constructor-arg>
            <ref bean="office" />
        </constructor-arg>
    </bean>
    <bean id="car" class="com.ioc.ch4_3_2.Car"/>
    <bean id="office" class="com.ioc.ch4_3_2.Office" />
 </beans>

测试类:

package com.ioc.ch4_3_2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by gao on 16-3-25.
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com\\ioc\\ch4_3_2\\beans.xml");
        Car car1 = (Car) ctx.getBean("car1");
        System.out.println(car1.toString());
        System.out.println("--------------------------------");
        Car car2 = (Car) ctx.getBean("car2");
        System.out.println(car2.toString());
        System.out.println("--------------------------------");
        Car car3 = (Car) ctx.getBean("car3");
        System.out.println(car3.toString());
        System.out.println("--------------------------------");
        Boss boss1 = (Boss) ctx.getBean("boss1");
        System.out.println(boss1.toString());
    }
}
输出结果:
brand:car1_甲壳虫 maxSpeed:0 price:300000.0 corp:null
--------------------------------
brand:car2_宝马 maxSpeed:300 price:200000.0 corp:null
--------------------------------
brand:car3_红旗CA72 maxSpeed:200 price:0.0 corp:中国一汽
--------------------------------
name:John car:car1_甲壳虫 office:com.ioc.ch4_3_2.Office@9eed10a
 
3、工厂方法注入
有非静态工厂方法和静态工厂方法两种方式
Car类:
package com.ioc.ch4_3_3;
/**
 * Created by gao on 16-3-25.
 */
public class Car {
    private int maxSpeed;
    public String brand;
    private double price;
    public Car() {
    }
    public Car(int maxSpeed, String brand, double price) {
        this.maxSpeed = maxSpeed;
        this.brand = brand;
        this.price = price;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getMaxSpeed() {
        return maxSpeed;
    }
    public String getBrand() {
        return brand;
    }
    public double getPrice() {
        return price;
    }
    public String toString() {
        return "brand:" + brand + "\tmaxSpeed:" + maxSpeed + "\tprice:" + price;
    }
}

CarFactory类:

package com.ioc.ch4_3_3;
public class CarFactory {
    //创建Car的工厂方法
   public Car createHongQiCar(){
       Car car = new Car();
       car.setBrand("car5_奔驰");
       return car;
   }
   //工厂类方法是静态的
   public static Car createCar(){
       Car car = new Car();
       return car;
   }
}

beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="carFactory" class="com.ioc.ch4_3_3.CarFactory"/>
    <bean id="car5" factory-bean="carFactory" factory-method="createHongQiCar"/>
    <bean id="car6" class="com.ioc.ch4_3_3.CarFactory" factory-method="createCar"/>
 </beans>

测试类:

package com.ioc.ch4_3_3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by gao on 16-3-25.
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com\\ioc\\ch4_3_3\\beans.xml");
        Car car5 = (Car) ctx.getBean("car5");
        System.out.println(car5.toString());
        System.out.println("-----------------------");
        Car car6 = (Car) ctx.getBean("car6");
        System.out.println(car6.toString());
    }
}
输出结果:
brand:car5_奔驰 maxSpeed:0 price:0.0
-----------------------
brand:null maxSpeed:0 price:0.0

 

注入方法的考量:
1)支持使用构造函数注入的理由:
    · 构造函数可以保证一些重要的属性在Bean实例化时就设置好,避免了因为一些重要属性没有提供,导致一个无用Bean实例的情况;
    · 不需要为每个属性提供Setter方法,减少了类的方法个数;    
    · 可以更好地封装类变量,不需要为每个属性指定setter方法,避免外部错误的调用。
2)更多的开发者更倾向于使用属性注入方式,反对构造函数注入的理由:
    · 如果一个类的属性众多,构造函数的签名将变成一个庞然大物,可读性很差;
    · 灵活性不强,在有些属性是可选的情况下,如果通过构造函数注入,也需要为可选的参数提供一个null值;
    · 如果有多个构造函数,需要考虑配置文件和具体构造函数匹配歧义的问题,配置上相对复杂;
    · 构造函数不利于类的继承和扩展,因为子类需要引用到父类复杂的构造函数;
    · 构造函数注入有时会造成循环依赖的问题。
3)对于一个全新的应用来说,不推荐使用工厂方法的注入方式。

 

 

 

目录
打赏
0
0
0
0
216
分享
相关文章
|
10天前
|
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
48 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
39 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
32 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
52 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
30 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
31 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
20 0
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
169 26
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式

热门文章

最新文章