Spring IOC(基於配置文件的方式)
阿新 • • 發佈:2018-07-03
interface ret ava package www app Coding factory get方法
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 inthour = 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 inthour = 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(基於配置文件的方式)