В предыдущей статье мы рассмотрели внедрение зависимостей через конструктор, теперь рассмотрим внедрение зависимостей через свойства.
Структура проекта:
DependentBean
:
package ru.mydesignstudio.spring.core.ioc.beans; public class DependentBean { private int someValue; public void setSomeValue(int someValue) { this.someValue = someValue; } }
И MainBean
:
package ru.mydesignstudio.spring.core.ioc.beans; public class MainBean { private DependentBean dependentBean; public void setDependentBean(DependentBean dependentBean) { this.dependentBean = dependentBean; } }
Описание контекста:
<?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="dependentBean" class="ru.mydesignstudio.spring.core.ioc.beans.DependentBean"> <property name="someValue"> <value>10</value> </property> </bean> <bean id="mainBean" class="ru.mydesignstudio.spring.core.ioc.beans.MainBean"> <property name="dependentBean"> <ref bean="dependentBean" /> </property> </bean> </beans>
Основной элемент здесь – property
. Задаем конкретное значение свойства:
<property name="someValue"> <value>10</value> </property>
Или ссылку на другой бин:
<bean id="mainBean" class="ru.mydesignstudio.spring.core.ioc.beans.MainBean"> <property name="dependentBean"> <ref bean="dependentBean" /> </property> </bean>
Получаем бин из контекста:
package ru.mydesignstudio.spring.core.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import ru.mydesignstudio.spring.core.ioc.beans.MainBean; public class Application { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("common.xml"); MainBean bean = context.getBean(MainBean.class); System.out.println(bean); } }
И смотрим на результат:
Возможно также использование пространства имен p
, которое позволяет сократить запись:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dependentBean" class="ru.mydesignstudio.spring.core.ioc.beans.DependentBean" p:someValue="1" /> <bean id="mainBean" class="ru.mydesignstudio.spring.core.ioc.beans.MainBean" p:dependentBean-ref="dependentBean" /> </beans>