Spring依赖注入(2)

介绍

前文介绍了Spring加载bean的3种机制 Spring依赖注入(1), 此时我们对bean的加载机制有了基本的认识,针对前文提出的问题进行整理。遗留问题包括

  1. Java配置类与XML配置相互配合
  2. 自动装配Bean歧义问题
  3. 类之外属性的注入
  4. 利用properties文件实现具体值注入等等

接下来我们来一一说明。

混合配置

JavaConfig之间引用

利用@Import注解引用其他的JavaConfig类,示例如下:

package com.notepad.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.notepad")
// 导入其他的JavaConfig类
@Import(SpringConfig.class)
public class DocConfig {
}

JavaConfig引用XML

利用@ImportResource注解引用XML配置,示例如下:

package com.notepad.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.notepad")
// 导入XML配置
@ImportResource("classpath:answer-bean.xml")
public class DocConfig {
}

XML配置之间引用

利用“import” 元素引用其他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.xsd">

    <!--XML之间的引用-->
    <import resource="answer-bean.xml"/>
</beans>

XML引用JavaConfig

利用“bean”引用JavaConfig类, 同加载普通类没有区别。示例如下:

<?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.xsd">

    <!--引用JavaConfig-->
    <bean class="com.notepad.spring.SpringConfig"/>
</beans>

Github代码

https://github.com/yangbigmeng/notepad

参考

Spring In Action(第四版). 第三章

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值