将new的过程交给Spring来管理:
常见运用,入service中常需要调用Dao层,而new的过程可以用配置的方式来实现;
即:在service里面将dao作为类型属性,生成dao类型的set方法,从而用set注入,将其注入;
可笑的是在刚开始写代码,配置文件写成了:
<!-- 在这里需要创建两个对象,service和dao的对象都要创建 -->
<bean id="testDao" class="newProject.TestDao"></bean>
<bean id="service" class="newProject.Service"></bean>
<!-- 注入dao对象,name属性值:为Service里面的要注入的属性名称,写ref属性为:dao配置bean标签中的id值
因为此处注入的是一个对象而不是某个字符串值,所以不能是value
-->
<bean>
<property name="dao" ref="testDao"></property>
</bean>
结果报错:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unnamed bean definition specifies neither 'class' nor 'parent' nor 'factory-bean' - can't generate bean name
Offending resource: class path resource [mapper/spring.xml]
正确代码:
public class Service {
private TestDao dao;
public void setDao(TestDao dao) {
this.dao = dao;
}
public void addService(){
System.out.println("service======");
dao.add();
}
}
//测试有参构造注入值:
@Test
public void test3(){
ApplicationContext con=new ClassPathXmlApplicationContext("mapper/spring.xml");
Service us=(Service) con.getBean("service");
us.addService();
}
<!-- 在这里需要创建两个对象,service和dao的对象都要创建 -->
<bean id="testDao" class="newProject.TestDao"></bean>
<bean id="service" class="newProject.Service">
<!-- 注入dao对象,name属性值:为Service里面的要注入的属性名称,写ref属性为:dao配置bean标签中的id值
因为此处注入的是一个对象而不是某个字符串值,所以不能是value
-->
<property name="dao" ref="testDao"></property>
</bean>
public class TestDao {
public void add(){
System.out.println("add方法====");
}
}