使用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  (组件)

这 个注释分别和持久层、业务层和控制层(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的注入注解方式


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


  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 使用Maven创建Spring项目的步骤如下: 1. 在Maven中创建一个新的项目,可以使用Maven的命令行工具或者Eclipse等集成开发环境来创建。 2. 在pom.xml文件中添加Spring的依赖,可以根据需要添加不同本的Spring依赖。 3. 创建Spring的配置文件,通常是applicationContext.xml文件,可以在其中定义Springbean、数据源、事务管理等。 4. 在Java代码中使用Spring注解或者XML配置来引用Springbean,可以使用@Autowired、@Resource等注解来注入bean。 5. 运行项目,可以使用Maven的命令行工具或者Eclipse等集成开发环境来运行项目。 总之,使用Maven创建Spring项目可以方便地管理项目的依赖和构建过程,同时也可以提高项目的可维护性和可扩展性。 ### 回答2: 在使用maven创建spring项目之前,确保你已经安装了Java和maven,并且设置好了环境变量。接下来,按照下面的步骤来使用maven创建spring项目: 1. 打开终端或命令行窗口,创建一个新的maven工程。输入以下命令: mvn archetype:generate -DgroupId=com.example -DartifactId=spring-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 2. 切换到项目文件夹。输入以下命令: cd spring-demo 3. 在项目的根目录下创建一个名为src/main/java的文件夹。 4. 在src/main/java中创建一个名为com.example的文件夹。 5. 在com.example文件夹中创建一个名为App.java的文件。 6. 在App.java中添加以下代码: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } 7. 在Spring框架中,要将控制权交给Spring容器,来管理其余的Bean。因此,需要在pom.xml文件中添加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 8. 使用maven编译项目,并运行程序。 mvn clean install mvn spring-boot:run 9. 打开浏览器,并输入http://localhost:8080/URL来查看应用程序。 通过这些步骤,您已经成功地使用maven创建了一个Spring项目。现在您可以开始开发您的应用程序。 ### 回答3: Maven是一个基于Java的自动化构建工具,它可以帮助我们管理项目依赖、编译、打包、发布等一系列操作。Spring则是一个流行的Java开发框架,它提供了全面的JavaEE开发解决方案。使用Maven创建Spring可以帮助我们更加方便地管理Spring框架的依赖、构建和发布。 下面是使用Maven创建Spring框架的步骤: 1. 安装Maven 首先需要在本机安装Maven,具体安装方法可以参考官方文档。确保在安装完Maven后,可以使用mvn命令在终端中运行Maven。 2. 创建Maven项目 使用Maven创建一个空的Java项目: ``` mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false ``` 这个命令会创建一个基于maven-archetype-quickstart的空Java项目,需要输入项目的groupId和artifactId以及一些其他信息。 3. 添加Spring依赖 在pom.xml文件中添加Spring的依赖: ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.4.RELEASE</version> </dependency> </dependencies> ``` 这里以spring-context为例,如果需要使用其他Spring模块,可以在dependencies标签中添加相应的依赖项。 4. 编写Spring配置文件 在src/main/resources目录下创建一个名为applicationContext.xml的Spring配置文件,定义Springbean等: ``` <beans> <bean id="helloWorld" class="com.example.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans> ``` 这里创建了一个名为helloWorld的bean,类型为com.example.HelloWorld,并设置了一个message属性。需要根据实际需要编写相应的配置文件。 5. 编写Java代码 在src/main/java目录下创建com.example包,并创建一个名为HelloWorld的Java类: ``` package com.example; public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("Message: " + message); } } ``` 这个类作为bean的实现类,并且可以通过Spring容器来管理。 6. 编译和运行 使用Maven进行编译: ``` mvn compile ``` 使用Maven运行程序: ``` mvn exec:java -Dexec.mainClass="com.example.App" ``` 其中com.example.App是定义的Java入口类。 至此,使用Maven创建了一个简单的Spring应用程序,并进行了编译和运行。在实际开发中,需要根据具体需求来添加更多的依赖、配置文件和Java代码。使用Maven来管理这些工作,可以极大地提高我们的开发效率和程序的可维护性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值