其他分享
首页 > 其他分享> > Spring初探(1)

Spring初探(1)

作者:互联网

简单的定义个接口

package com.spring.service;

public interface IService {
	void doSome();
}

写接口的实现类

package com.spring.service;

public class SomeServiceImp implements IService {

	@Override
	public void doSome() {
		System.out.println("执行doSome");
	}
	
}

配置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
         http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="myService" class="com.spring.service.SomeServiceImp" ></bean>
	
</beans>

定义测试类

package com.spring.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.spring.service.IService;
import com.spring.service.SomeServiceImp;

public class MyTest {
	@Test
	public void test() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		IService service = (IService) ac.getBean("myService");
		
		service.doSome();
	}
	
	@Test
	public void test1() {
		ApplicationContext ac = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
		
		IService service = (IService) ac.getBean("myService");
		
		service.doSome();
	}
	@Test
	public void test2() {
//		ApplicationContext ac = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
		
		BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		
		IService service = (IService) factory.getBean("myService");
		
		service.doSome();
	}
}
	三种方法皆能得到运行结果

Spring jar包下载网址:https://repo.spring.io/release/org/springframework/spring/

标签:IService,service,spring,Spring,初探,import,org,public
来源: https://blog.csdn.net/qq_38106680/article/details/99295511