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