欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

java_spring_依赖注入(构造器)

发布时间:2025/3/17 编程问答 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java_spring_依赖注入(构造器) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

依赖注入对象可以 手工装配(建议) 和 自动装配


package com.PersonDaoBean.test;public interface PersonDao {public abstract void add();}



package com.PersonDaoBean.test;public class PersonDaoBean implements PersonDao {@Overridepublic void add(){System.out.println("PersonDaoBean执行。。。。。。。。。。。。。。。。。");} }



package com.dao.bean.www;public interface PersonServiceDao {public abstract void save();}



package com.bean.www;import com.PersonDaoBean.test.PersonDao; import com.dao.bean.www.PersonServiceDao;public class PersonServiceBean implements PersonServiceDao {private PersonDao personDao;private String name;public PersonServiceBean(PersonDao personDao, String name) {this.personDao = personDao;this.name = name;}public void save() {personDao.add();System.out.println(name);}}


//配置方法

<?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-3.0.xsd"><bean id="personDao" class="com.PersonDaoBean.test.PersonDaoBean"></bean><bean id="personService" class="com.bean.www.PersonServiceBean"><constructor-arg index="0" type="com.PersonDaoBean.test.PersonDao" ref="personDao"></constructor-arg><constructor-arg index="1" value="valueString"></constructor-arg></bean></beans>



//Test Class

package com.itcast.www;import static org.junit.Assert.*;import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.dao.bean.www.PersonServiceDao;public class TestCaseDemo {@BeforeClasspublic static void setUpBeforeClass() throws Exception {}@Testpublic void instanceSpring() {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");PersonServiceDao personService = (PersonServiceDao) ctx.getBean("personService");personService.save();}}























































































































 

转载于:https://www.cnblogs.com/MarchThree/p/3720410.html

总结

以上是生活随笔为你收集整理的java_spring_依赖注入(构造器)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。