ITeye博客

spring4学习(一)基础配置

sb33060418 · 2017-05-05 17:13 · spring · Web前端 · Spring · Markdown

记录下Spring4的基础用法。 环境:Myeclipse10.6+jdk7 库:spring4.1.6 [b]1.创建项目[/b] 在Myeclipse中配置Maven相关属性,创建基于Maven的java工程testSpring。 [b]2.添加依赖库[/b] 在pom.xml中添加spring依赖。 [code="java"] org.springframework spring-context 4.1.6.RELEASE [/code] [b]3.定义接口[/b] spring的基本调用方法是在启动程序中加载配置并创建ApplicationContext,通过ApplicationContext获取Service Bean和Dao Bean并注入,再调用Bean中的业务方法。 目录结构如下: [code="java"]src --main ----java ------com.sunbin.test.testSpring --------main ----------测试运行类 --------service ----------service接口类 ----------impl ------------service实现类 --------dao ----------dao接口类 ----------impl ------------dao实现类 ----resources ------spring配置文件[/code] 定义service接口TestService。 [code="java"] package com.sunbin.test.testSpring.service; public interface TestService { public String test(String string); } [/code] 定义dao接口TestDao。 [code="java"] package com.sunbin.test.testSpring.dao; public interface TestDao { public String test(String string); } [/code] [b]4.实现接口[/b] 简单实现service接口。 [code="java"] package com.sunbin.test.testSpring.service.impl; import com.sunbin.test.testSpring.dao.TestDao; import com.sunbin.test.testSpring.service.TestService; public class TestServiceImpl implements TestService { private TestDao testDao; public String test(String string) { // TODO Auto-generated method stub return "testServiceImpl.test:"+testDao.test(string); } public TestDao getTestDao() { return testDao; } public void setTestDao(TestDao testDao) { this.testDao = testDao; } } [/code] 实现dao接口。 [code="java"] package com.sunbin.test.testSpring.dao.impl; import com.sunbin.test.testSpring.dao.TestDao; public class TestDaoImpl implements TestDao { @Override public String test(String string) { // TODO Auto-generated method stub return "testDaoImpl.test:"+string; } } [/code] [b]5.spring配置[/b] 在src/main/resources下创建配置文件root-context.xml,内容如下: [code="java"] [/code] 配置中载入其他配置文件。 services.xml中定义service层Bean: [code="java"] [/code] dao.xml中定义dao层Bean: [code="java"] [/code] 通过设置default-autowire="byName",spring会自动查找名为testDao的Bean(dao.xml中定义),并通过TestServiceImpl类的setter方法注入testService Bean。 [b]6.测试[/b] 创建测试类Test。 [code="java"] package com.sunbin.test.testSpring.main; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sunbin.test.testSpring.service.TestService; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "root-context.xml" }); TestService testService =(TestService) applicationContext.getBean("testService"); System.out.println(testService.test("helloWorld")); } } [/code] 测试类中加载spring配置、创建ApplicationContext、获取Service Bean(Dao Bean被注入)。 运行结果如下: [list] [*]testServiceImpl.test:testDaoImpl.test:helloWorld [/list] 说明Test、Service、Dao各层创建、注入、调用成功。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。