美文网首页
Spring的搭建

Spring的搭建

作者: 傲慢与偏见_6c6c | 来源:发表于2018-03-11 18:27 被阅读0次

    2018-03-03

    我用的是eclipse搭建的web项目

    (1)导入必要的jar包,总共四个,还要加上2个常用的日志jar包

    +commons-logging-1.1.3.jar + log4j-1.2.15.jar

    (2)在src(建议在src目录下建立applicationcontext.xml文件(名字可随便起))

    网页最下面可以看到(不包含注解约束)

    配置(约束).dtd文件Window-->Preferencs-->搜索XML-->Catalog-->add-->

    此时注意Key type那栏改成Schema location 测试使用

    (二,注解形式)

    jar包:

    使用注解的包

    ②:配置文件添加注解约束“

    注解约束

    :③:创建类-->方法-->测试类-->Service类

    (注解有@Component/Controller/Service/Repository)

    @Component("user")-----注解自动创建对象

    在service层得到dao对象可以用@autowired,更建议用@Resource(name=" ")在service引入dao对象

    <三>Spring 的aop操作:

    在spring里面进行aop,使用aspectj(aspectj-不是spring的一部分,和spring一起使用进行aop操作)

    ①jar包:aopalliance.jar  +  aspectjweaver.jar  +  spring-aop-3.2.17.RELEASE.jar  +  spring-aspects-3.2.17.RELEASE.jar

    ②导入aop约束:E.2.7 Theaopschema

    xmlns:aop="http://www.springframework.org/schema/aop"

    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

    ③,写配置文件:


    *关于增强的测试代码:

    ①public class Book {

      public void add(){

      System.out.println("被增强发法。。。。。");

      }

    }

    ②public class MyBook {

      public void before(){

      System.out.println("前置增强。。。");

      }

      public void after(){

      System.out.println("后置增强。。。");

      }

      public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{

      System.out.println("环绕方法前。。。");

      //执行被增强方法

      proceedingJoinPoint.proceed();

      System.out.println("环绕方法后。。。");

      }

    }

    ③public class ZengqiangTest {

    @Test

    public void testZengqiang(){

    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

    Book book=(Book) context.getBean("book");

    book.add();

    }

    }

    *(控制台出现警告是因为少了log4j.properties 可自行设置日志等级)

    Spring整合web项目实际操作:

    ①添加Struts2的jar包,web.xml配置过滤器,监听(监听是为了在服务器启动的时候就创建对象,加载applicationContext.xml配置,提高运行效率----配置监听器之前要确定已经导入了,spring整合web项目的jar包spring-web-3.2.17.RELEASE.jar)

    1.1监听器:

    注意!!!这个不是选红线那个,选下面这个...Listener spring-web-3.2.17.RELEASE-sources.jar   找到这个打开 我觉得你们可以直接复制:org.springframework.web.context.ContextLoaderListener

    ②请记住:监听器默认是找/WEB-INF/目录下的applicationContext.xml文件,但是我们写在了Src目录下,

    所以我们还要指定加载spring配置文件路径:

    <!--指定加载spring配置文件位置(想知道spring加载配置源代码自己搜吧)-->

    <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:applicationContext.xml</param-value>

    </context-param>

                                                                                                 ----文章作者原创,欢迎大家借鉴,指正

    相关文章

      网友评论

          本文标题:Spring的搭建

          本文链接:https://www.haomeiwen.com/subject/vsatfftx.html