JavaWeb笔记011 Spring配置文件属性注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lizhengwei1989/article/details/88563672

上一篇博文中介绍了Spring中配置bean的方法。那么问题来了,如果bean中有一些参数是依赖了另外一些bean或者是另外一些参数该怎么配置呢?这篇博文就说说如何解决这个问题

1.set方法注入

例如:如果UserServiceImpl的实现类中有一个属性,那么使用Spring框架的IOC功能时,可以通过依赖注入把该属性的值传入进来!!
具体的配置如下
		<bean id="us" class="com.demo1.UserServiceImpl">
			<property name="uname" value="小风"/>
		</bean>
		类如下
        public class UserServiceImpl implements UserService {
        	private String name;
        	public void setName(String name) {
        		this.name = name;
        	}
            ...
        }
        <!-- 演示的依赖注入,依赖的是类,不是字符串,用ref属性 -->
        <bean id="customerDao" class="com.demo3.CustomerDaoImpl"/>
        <bean id="customerService" class="com.demo3.CustomerServiceImpl">
           <property name="customerDao" ref="customerDao"/>
        </bean>
        public class CustomerServiceImpl {
        	// 提供成员属性,提供set方法
        	private CustomerDaoImpl customerDao;
        	public void setCustomerDao(CustomerDaoImpl customerDao) {
        		this.customerDao = customerDao;
        	}
        	
        	public void save(){
        		System.out.println("我是业务层service....");
        		customerDao.save();
        	}
        
        }

2.构造方法的注入方式

编写Java的类,提供构造方法
			public class Car {
				private String name;
				private double money;
				public Car(String name, double money) {
					this.name = name;
					this.money = money;
				}
				@Override
				public String toString() {
					return "Car [name=" + name + ", money=" + money + "]";
				}
			}
		
编写配置文件,如果构造中有引用,用ref=""代替value
			<bean id="car" class="com.demo4.Car">
				<constructor-arg name="name" value="大奔"/>
				<constructor-arg name="money" value="100"/>
			</bean>

3.集合(List,Set,Map)的注入

1. 如果是数组或者List集合,注入配置文件的方式是一样的
	<bean id="collectionBean" class="com.itheima.demo5.CollectionBean">
		<property name="arrs">
			<list>
				<value>美美</value>  // 如果是对象类型<ref bean="引用"/>,set集合均相同
				<value>小风</value>
			</list>
		</property>
	</bean>

2. 如果是Set集合,注入的配置文件方式如下:
	<property name="sets">
		<set>
			<value>哈哈</value>
			<value>呵呵</value>
		</set>
	</property>

3. 如果是Map集合,注入的配置方式如下:
	<property name="map">
		<map>
			<entry key="老王2" value="38"/> // 对象是<entry key-ref="老王2" value-ref="38"/>
			<entry key="凤姐" value="38"/>
			<entry key="如花" value="29"/>
		</map>
	</property>

4.Spring框架的配置文件分开管理

例如:在配置文件夹下多创建了一个配置文件,现在是两个核心的配置文件,那么加载这两个配置文件的方式有两种!
	* 主配置文件中包含其他的配置文件:
		<import resource="applicationContext2.xml"/>
	
	* 工厂创建的时候直接加载多个配置文件:
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
					"applicationContext.xml","applicationContext2.xml");

猜你喜欢

转载自blog.csdn.net/lizhengwei1989/article/details/88563672