spring 依賴注入的學習

久夢歌行發表於2014-12-27

DI:Dependency Injection 依賴注入,在Spring框架負責建立Bean物件時,動態的將依賴物件注入到Bean元件


由於物件是由spring建立的,可以在service中

public class HelloService implements IHelloService {
	private String info;
	
	@Override
	public void sayHello() {
		System.out.println("hello world"+info);
	}
	
	public void setInfo(String info) {
		this.info = info;
	}
	
	
}

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">
	<!-- 配置哪個類對IHelloService例項化 -->
	<bean id="helloService" class="cn.spring.service.impl.HelloService">
		<!-- 依賴info屬性 -->
		<property name="info" value=" haha"></property>
	</bean>

</beans>

測試例子中

	public void test2() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//配置檔案中的id屬性
		IHelloService service = (IHelloService) context.getBean("helloService");
		service.sayHello();
		
	}


相關文章