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();

猜你喜欢

转载自blog.csdn.net/xuejianbest/article/details/86503190