Spring IOC(基于配置文件的方式)

IDao.java

1 package com.spring.ioc;
2 
3 public interface IDao {
4     public String sayHello(String name);
5 }

DaoImpl.java

 1 package com.spring.ioc;
 2 
 3 import java.util.Calendar;
 4 
 5 public class DaoImpl implements IDao {
 6     @Override
 7     public String sayHello(String name) {
 8         int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
 9         if (hour<6) return "凌晨早,"+name;
10         if (hour<12) return "早上好,"+name;
11         if (hour<13) return "中午好,"+name;
12         if (hour<18) return "下午好,"+name;
13         return "晚上好,"+name;
14     }
15 }

IService.java

1 package com.spring.ioc;
2 
3 public interface IService {
4     public void service(String name);
5 }

ServiceImpl.java

 1 package com.spring.ioc;
 2 
 3 import java.util.Calendar;
 4 
 5 public class DaoImpl implements IDao {
 6     @Override
 7     public String sayHello(String name) {
 8         int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
 9         if (hour<6) return "凌晨早,"+name;
10         if (hour<12) return "早上好,"+name;
11         if (hour<13) return "中午好,"+name;
12         if (hour<18) return "下午好,"+name;
13         return "晚上好,"+name;
14     }
15 }

在src文件夹下新建application.xml中配置相关的javabean

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="daoImpl" class="com.spring.ioc.DaoImpl"></bean>
 7 
 8     <bean id="serviceImpl" class="com.spring.ioc.ServiceImpl">
 9         <property name="dao" ref="daoImpl"></property>
10     </bean>
11     <!--property把service的dao属性设为daoImpl,相当于java代码:
12     service.setDao(Impl)
13     将对象的创建和初始化交给xml文件
14     前提是:对应的javaBean中应该提供set和get方法-->
15 </beans>

测试类:TestSpring.java

 1 package com.spring.ioc;
 2 
 3 import org.codehaus.xfire.xmlbeans.XmlBeansServiceFactory;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 import org.springframework.core.io.ClassPathResource;
 7 
 8 public class SpringTest {
 9     public static void main(String[] args) {
10         //创建一个bean工厂
11         ApplicationContext context = new ClassPathXmlApplicationContext(
12                 "applicationContext.xml");
13         IService hello = (IService) context.getBean("serviceImpl");
14         hello.service("helloween");
15         ((ClassPathXmlApplicationContext) context).destroy();
16     }
17 }

 

转载于:https://www.cnblogs.com/ditto/p/9260752.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值