Spring:一般注入的xml配置文件

依赖注入

spring在初始化上行文的时候会初始化所有的bean。

也就是在执行
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
的时候会运行所有bean的构造方法初始化bean类。

此后不再进行注入操作,因此代码中手动初始化的类不会进行注入。

用上下文(context)的getBean方法获取到的类是初始化上下文时注入好的bean类。

被继承的父类初始化时也不会进行注入,因为这相当于手动调用了父类的构造方法。

只有从上下文环境中获取的bean类才是注入好的。


构造器注入

<constructor-arg>子标签传递构造参数;

factory-method属性调用静态方法获取实例;

scope属性指定spring容器初始化bean的方式,如:

  • scope="singleton":一个spring容器只实例化一个bean,每次调用的bean都是同一个实例,此为默认。

  • scope="prototype":每次调用spring都会初始化一个单独的实例出来。

此外scope取值还可以为requestsessionglobal-session

init-method属性指定在初始化bean后立即调用的方法;

destroy-method属性指定在销毁bean前调用的方法。

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

    <bean id="accountDao" class="org.springframework.samples.dao.JpaAccountDao">
        <constructor-arg ref="dog1" />
        <constructor-arg value="10" />
    </bean>

    <bean id="itemDao" class="org.springframework.samples.dao.JpaItemDao" factory-method="getInstance">
        <!-- 在这里写额外的bean的配置和相关引用 -->
    </bean>

    <!-- 更多数据访问层的bean定义写在这里 -->
</beans>
属性注入
<?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">

    <!-- services -->

    <bean id="petStore" class="org.springframework.samples.service.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- 在这里写额外的bean的配置和相关引用 -->
    </bean>

    <!-- 更多Service层的bean定义写在这里 -->
</beans>
引用其他文件
<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>
    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>
通过上下文获得bean
// create and configure beans
ApplicationContext context =
    new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

转载于:https://www.cnblogs.com/xuejianbest/p/10284919.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值