Spring IOC(基于配置文件的方式)
Posted ditto
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Spring IOC(基于配置文件的方式)的主要内容,如果未能解决你的问题,请参考以下文章
Spring IOC 系列:基于Java Code 配置Spring Container
Spring讲解二:Spring中的Bean配置1---基于XML文件的方式