天天看點

使用Maven使用spring(注解版)

接上一篇:使用Maven配置spring

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  (元件)

這 3 個注釋分别和持久層、業務層和控制層(Web 層)相對應。雖然目前這 3 個注釋和 @Component 相比沒有什麼新意,但 Spring 将在以後的版本中為它們添加特殊的功能。是以,如果 Web 應用程式采用了經典的三層分層結構的話,最好在持久層、業務層和控制層分别采用 @Repository、@Service 和 @Controller 對分層中的類進行注釋,而用 @Component 對那些比較中立的類進行注釋。

要點3:scope

表示該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

@Autowired是Spring 提供的,需導入

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

隻按照byType 注入。一個參數  required,Boolean 是否必須

@Resource

@Resource(name="12",type=App.class)(兩個比較重要的參數)

@Resource預設按 byName 自動注入,是J2EE提供的, 需導入Package:

javax.annotation.Resource;

@Resource有兩個中重要的屬性:name和type ,而Spring将@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。是以如果使用name屬性,則使用byName的自動注入政策,而使用type屬性時則使用 byType自動注入政策。如果既不指定name也不指定type屬性,這時将通過反射機制使用byName自動注入政策。

@Resource裝配順序

(1). 如果同時指定了name和type,則從Spring上下文中找到唯一比對的bean進行裝配,找不到則抛出異常;

(2). 如果指定了name,則從上下文中查找名稱(id)比對的bean進行裝配,找不到則抛出異常;

(3). 如果指定了type,則從上下文中找到類型比對的唯一bean進行裝配,找不到或者找到多個,都會抛出異常;

(4). 如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配;如果沒有比對,則回退為一個原始類型進行比對,如果比對則自動裝配;

@Resource的作用相當于@Autowired,隻不過@Autowired按byType自動注入。

     Qualifier

使用 @Qualifier 注釋指定注入 Bean 的名稱

     一般使用方法

 @Autowired

 @Qualifier("person")

或者@Qualifier("person")

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

4、配置JUNIT測試環境

目錄結構

使用Maven使用spring(注解版)

在上次的基礎上,建立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());

  }

}

說明:給測試類注入了app,app裡又注入了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裡的預設屬性。

說明1:junit4.10不是所有版本的spring-test都能搭配的,如果運作報錯,看下junit和spring-test的搭配問題

說明2:spring的注入注解方式

下一篇: spring加入hibernate(注解版)

繼續閱讀