多语言展示
当前在线:1042今日阅读:138今日分享:34

Spring基础配置

Spring基础配置
工具/原料
1

spring

2

eclipse

方法/步骤
1

在整个的开发过程之中,首先值能够通过代码物劫来感受一下spring基础配置,而如果你要想感受到这种spring的完整的优点,需要经过更多的学习。1、将之前接口和实现类的代码拷贝到项目之中。拷贝到src/main/java目录之中。

2

修改applicationContext.xml配置文件:               

3

此时为一个具体的子类设置了一个引用的名称。编写一个测试的程序代码类:spring是一个容器所以需要先模拟该容器的启动,这里面需要使用一些spring自己的类。要通过资源文件取得IMessageService接口对象。package com.gwolf.service.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.gwolf.service.IMessageService;public class TestMessage {        public static void main(String[] args) {                //加载applicationContext.xml文件,同时表示spring的容器启动                ApplicationContext applicationContext =                                 new ClassPathXmlApplicationContext('applicationContext.xml');                                IMessageService messageService = applicationContext.getBean('msg',IMessageService.class);                                System.out.println(messageService.info());        }}

4

既然都已经设计到开发框架,而且开发框架里面已经配置好了一个常用的日志组件:log4j、slf4j。建议在src/main/resourcces目录里面拷贝一个log4j.xml文件。                     久敏              

6

既然都使用到了maven开发,那么对于代码的测试就不要再去写测试类,应该使用junit测试。package com.gwolf.service.test;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.gwolf.service.IMessageService;import junit.framework.Assert;import junit.framework.TestCase;public class TestMessage {        //加载applicationContext.xml文件,同时表示spring的容器启动        private static ApplicationContext applicationContext = null;                static {                applicationContext = new ClassPathXmlApplicationContext('applicationContext.xml');        }                                @Test        public void testMsg() {                IMessageService messageService = applicationContext.getBean('msg',IMessageService.class);                                Logger log = LoggerFactory.getLogger(TestMessage.class);                                log.info(messageService.info());                                TestCase.assertEquals(messageService.info(), 'www.baidu.com');        }}

7

在maven项目里面提供有整体的测试操作,所以建议整体运行maven test。

8

通过以上的配置就可以发现在整个spring里面对于对象的产生完全有spring自己来维护,这样的开发是有好处的,这样就避免了关键字new。现阶段通过java程序启动了spring容器,而后可以利用web容器来启动spring容器,整个的处理里面你不会再看见任何的关键字new的出现。

推荐信息