`

[转]使用Maven使用spring(注解版)

阅读更多

转自:http://blog.csdn.net/shiyuezhong/article/details/7959888/

1.用到的依赖包

   Pom.xml添加:

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-test</artifactId>

        <version>3.0.0.RELEASE</version>

        <type>jar</type>

        <scope>compile</scope>

</dependency>     

   <dependency>

        <groupId>junit</groupId>

        <artifactId>junit</artifactId>

        <version>4.10</version>

        <type>jar</type>

        <scope>test</scope>

  </dependency>

注:junit从上回的3换到了4.10

2.配置注解的application.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" xmlns:context="http://www.springframework.org/schema/context"

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

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

 

   <!--  <bean id="person" class="com.syz.test01.Person">

       <property name="name" value="zhangsan"></property>

       <property name="age" value="12"></property>

</bean>

<bean id="app" class="com.syz.test01.App">

   <property name="person" ref="person"></property>

</bean> -->

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

</beans>

注释掉原来的,加入类(红色部分,不加也行)和要扫描的包(下面讲到)。

3.配置被用来注入的类

先上类

package com.syz.test01;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import javax.annotation.PreDestroy;

 @Service("app")

@Scope("singleton")

public class App{

         @Autowired

         @Qualifier("person")

         public Person person;

         public Person getPerson() {

            return person;

         }

         @PostConstruct

        public void init(){

             System.out.println("app 在初始化!");

        }

        @PreDestroy

        public void destory(){           

        System.out.println("app 被销毁!");

     }

}

 

 

 

@Service("app")

要点1:用于注解类,表示该类会被spring扫描到

要点2:这几个用法功能一致

@Controller (控制层)

Indicates that an annotated class is a "Controller" (e.g. a web controller).

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

 

 

@Repository (持久层)

Indicates that an annotated class is a "Repository" (or "DAO").

 

A class thus annotated is eligible for Spring DataAccessException translation. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tools, aspects, etc.

As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

 

@Service  (业务层)

Indicates that an annotated class is a "Service" (e.g. a business service facade).

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

 

 

@Component  (组件)

这 个注释分别和持久层、业务层和控制层(Web )相对应。虽然目前这 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository@Service 和 @Controller 对分层中的类进行注释,而用 @Component 对那些比较中立的类进行注释。

要点3scope

表示该bean的作用域,

@Scope("singleton")

 

"singleton" and "prototype"

默认单例模式

 

要点4

@PostConstruct  定义该bean初始化前执行的函数

@PreDestroy     定义该bean销毁前执行的函数

该两个注解以及接下来的@Resource不是spring的, 是Java ee自带的。

 

要点5:注入

@Autowired

@Retention(value=RUNTIME)

@Target(value={CONSTRUCTOR,FIELD,METHOD})

public @interface Autowired

@AutowiredSpring 提供的,需导入

Package:org.springframework.beans.factory.annotation.Autowired;

只按照byType 注入。一个参数  requiredBoolean 是否必须

@Resource

@Resource(name="12",type=App.class)(两个比较重要的参数)

@Resource默认按 byName 自动注入,J2EE提供的, 需导入Package:

javax.annotation.Resource;

@Resource有两个中重要的属性:nametype ,而Spring@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用 byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource装配顺序

(1). 如果同时指定了nametype,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常;

(2). 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常;

(3). 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常;

(4). 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

 

@Resource的作用相当于@Autowired,只不过@AutowiredbyType自动注入。

     Qualifier

使用 @Qualifier 注释指定注入 Bean 的名称

     一般使用方法

 @Autowired

 @Qualifier("person")

或者@Qualifier("person")

或者@Resource(name="app",type=App.class)

4、配置JUNIT测试环境

目录结构

 

在上次的基础上,创建src/test/resources源文件夹

applicationContext-test.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" xmlns:jee="http://www.springframework.org/schema/jee"

    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

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

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"

    default-lazy-init="true">

<context:component-scan base-package="com.syz.test01" />

</beans>

只需配置要扫描的包就行了

log4j.properties:

# Output pattern : date [thread] priority category - message

log4j.rootLogger=debug,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

log4j.logger.org.springframework.beans.factory.annotation=debug,stdout

 

log4j.appender.F = org.apache.log4j.DailyRollingFileAppender

log4j.appender.F.file=d:\\login.log

log4j.appender.F.DatePattern='.'yyyy-MM-dd

log4j.appender.F.layout=org.apache.log4j.PatternLayout

log4j.appender.F.layout.ConversionPattern= %5r %-5p %c{2} - %m%n

日志输出的配置,看个人喜好

测试类:

package com.syz.test01;

import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

@ContextConfiguration(locations = { "/applicationContext-test.xml" })

public class AppTest extends AbstractJUnit4SpringContextTests{

 @Autowired

 @Qualifier("app")

 public App app ;

     public App getApp() {

          return app;

     }

    public void setApp(App app) {

        this.app = app;

     }

@Test

public void testApp(){

  System.out.println(app.getPerson().getName());

  System.out.println(app.getPerson().getAge());

  }

}

说明:给测试类注入了appapp里又注入了person,在该测试类中,就能拿到app中的person对象,并打印出来。

Person.java

package com.syz.test01;

import org.springframework.stereotype.Component;

 

@Component

public class Person {

    public String name = "zhangsan";

    public String age = "1";

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public String getAge() {

       return age;

    }

    public void setAge(String age) {

        this.age = age;

     }

 }

预计的效果是控制台能打印出person里的默认属性。

说明1junit4.10不是所有版本的spring-test都能搭配的,如果运行报错,看下junitspring-test的搭配问题

说明2spring的注入注解方式

分享到:
评论

相关推荐

    springmvc+mybatis+spring注解

    基于maven构建,采用注解方式,对项目要求不高的可以使用

    spring boot + mybaits +freemarker +maven 架构来袭 注解版

    spring boot + mybaits +freemarker +maven 架构来袭 注解版 spring boot + mybaits +freemarker +maven 架构来袭 注解版

    Maven struts-spring-hibernate全注解 通用CRUD示例

    1.引入Spring全注解 2.抽取业务/持久层通用代码(UniversalService/UniversalDao),避免重复编写 比如有实体:tab1,tab2,tab3,现在要对其3张表CRUD(增删改查)操作: a.使用原始的方法要写业务/持久类,至少各3,计6...

    Maven Struts-Spring-Hibernate全注解示例

    Maven:3.0.5 struts2.2.3-spring3.0.6-hibernate3.6.6 二、Demo功能(导入sql可直接运行) 1.数据库文件doc/db.sql 2.全注解,实现零配置 3.对Service/Dao层做了封装: 实现了对任何通用CRUD(增删改查)操作,不用写...

    Spring 4 + Mybatis 3 注解事务

    Spring 与 各框架的组各下来,版本就特别的多,针对简单的 使用注解来管理事务的,研究了两天,要不网上...说一下环境 Intellij Idea 15 + Maven + Spring 4.25 + Mybatis 3使用注解的方式,进行的事务回滚,欢迎测试。

    spring4.06 hibernate4.31 struts2.3.16 全注解MAVEN环境搭建

    最新版本的SPRING、HIBERNATE、STRUTS使用MAVEN搭建了一个全注解的环境。

    hessian 基于spring的注解支持的maven工程(2016/07/05版)

    引入该工程,在接口上添加@hessianService注解,在client定义url,在client端的xml里面配置hessianClientBuilder,在server里面配置hessianServerBuilder,并实例化接口。在client端里面使用接口并注入即可。

    spring结合mongodb例子(maven java project)

    通过spring-test的注解方式加载配置文件:AppTest2.java b.通过ApplicationContext applicationContext = new ClassPathXmlApplicationContext("mongo.xml");加载方式:App.java 3.列出log日志的java代码获取方式

    基于SpringMVC+Spring+MyBatis个人技术博客系统源码.zip

    基于SpringMVC+Spring+MyBatis个人技术博客系统源码.zip 完整代码,可运行 项目描述 基于SSM实现的一个个人博客系统,适合初学SSM和个人博客制作的同学学习。...代码中多次使用 @Data 注解,请确保你的 IDE

    Jersey Spring Integration Demo

    也是我们常用的IOC在java下一种实现了,不过相对.net下IOC的实现,Spring相对更强大(反正之前在.Net下,我是习惯了啥都去配置,在Java下才知道有一种Scan模式,本Demo中也用到了,不知道的可以查查spring 注解)。...

    尚硅谷-SpringBoot视频

    SpringBoot是企业级开发的整体整合解决方案,特别用于快速构建微服务应用,旨在用最简单的方式让开发人员适应各种开发场景; 本视频着重介绍SpringBoot的使用和内部原理;...最好配合《Spring注解版》一起学习效果更好

    基于Spring MVC的web框架 1.1.11

    工具类数据校验 jsp自定义标签 Spring自定义注解 默认requestMapping 1.1.2 代码生成器 1.1.3 首页修改 dateformat.js 时间参数转换 SpringMVC配置文件集中 快递参数接口 1.1.4 des加解密字符串和文件 1.1.5 redis...

    Spring in Action(第2版)中文版

    a.2把spring添加为一个maven2依赖项 a.3spring与ant a.4spring与log4j 附录b用(和不用)spring进行测试 b.1测试简介 b.1.1理解不同类型的测试 b.1.2使用junit b.1.3spring在测试中的角色 b.2单元测试...

    Spring+SpringMVC+Hibernate非注解版

    Spring+SpringMVX+Hibernate+Mysql在idea中Maven环境下配置

    Spring in Action(第二版 中文高清版).part2

    A.2 把Spring添加为一个Maven 2依赖项 A.3 Spring与Ant A.4 Spring与Log4j 附录B 用(和不用)Spring进行测试 B.1 测试简介 B.1.1 理解不同类型的测试 B.1.2 使用JUnit B.1.3 Spring在测试中的角色 B.2 单元...

    Spring in Action(第二版 中文高清版).part1

    A.2 把Spring添加为一个Maven 2依赖项 A.3 Spring与Ant A.4 Spring与Log4j 附录B 用(和不用)Spring进行测试 B.1 测试简介 B.1.1 理解不同类型的测试 B.1.2 使用JUnit B.1.3 Spring在测试中的角色 B.2 单元...

    spring mvc+hibernate 实现事务管理(全注解版)

    spring mvc hibernate 实现事务管理 jar包管理用maven,启动服务器用jetty,里边还有memcached数据库,但是本例子没有用到。

    尚硅谷Java视频教程_SpringBoot视频教程

    SpringBoot是企业级开发的整体整合解决方案,特别用于快速构建微服务应用,旨在用最简单的方式让开发人员适应各种开发场景; 本视频着重介绍SpringBoot的使用和内部原理;...最好配合《Spring注解版》一起学习效果更好

    尚硅谷全网最强SpringBoot视频

    SpringBoot是企业级开发的整体整合解决方案,特别用于快速构建微服务应用,旨在用最简单的方式让开发人员适应各种开发场景; 本视频着重介绍SpringBoot的使用和内部原理;...最好配合《Spring注解版》一起学习效果更好

    spring整合mybatis案例

    详细的spring整合mybatis案例,使用maven管理项目,spring4.0,mybatis3.0,注解详细,使用junit进行测试,附带了mysql绿色版以及相关的sql建库语句等等。

Global site tag (gtag.js) - Google Analytics