标签:容器 spring Fruit fruit com guan import IOC public
-
创建相关的类(这里是直接在之前类的基础上进行修改)
package com.guan.dao; public interface Fruit { String getFruit(); }
package com.guan.dao; public class FruitImpl implements Fruit { public String getFruit() { return "Buy Some fruit"; } }
package com.guan.service; import com.guan.dao.Fruit; public interface UserService { String buyFruit(); void setFruit(Fruit fruit); }
package com.guan.service; import com.guan.dao.Apple; import com.guan.dao.Fruit; import com.guan.dao.FruitImpl; public class UserServiceImpl implements UserService{ Fruit fruit; public UserServiceImpl() { fruit = new FruitImpl(); } public String buyFruit() { return fruit.getFruit(); } public void setFruit(Fruit fruit){ this.fruit = fruit; } }
-
在resources目录下添加配置文件:beans.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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="fruit" class="com.guan.dao.FruitImpl"></bean> <bean id="apple" class="com.guan.dao.Apple"></bean> <bean id="userService" class="com.guan.service.UserServiceImpl"> <property name="fruit" ref="fruit"></property> </bean> </beans>
注:
(1).即便没有属性需要初始化也需要通过
<bean>
来对其进行实例化,而不再需要new(2).
<property>
的注入需要类中存在set方法(3).对于属性的赋值的两种方式
- 对于基本类型的赋值可以用value属性
- 对于对象类型可以用ref(reference)属性以及
<bean>
中的id初始化
-
创建并使用实例
import com.guan.dao.Fruit; import com.guan.service.UserService; import com.guan.service.UserServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { //create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //retrieve configured instance UserService userService = (UserService) context.getBean("userService"); System.out.println(userService.buyFruit()); } }
标签:容器,spring,Fruit,fruit,com,guan,import,IOC,public 来源: https://www.cnblogs.com/Arno-vc/p/13387076.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。