前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >spring in action 4th --- quick start

spring in action 4th --- quick start

作者头像
Ryan-Miao
发布于 2018-03-13 05:41:39
发布于 2018-03-13 05:41:39
74200
代码可运行
举报
文章被收录于专栏:Ryan MiaoRyan Miao
运行总次数:0
代码可运行

读spring in action. 

  1. 环境搭建
  2. quick-start依赖注入
  3. 面向切面

1.环境搭建

  • jdk1.8
  • gradle 2.12
  • Intelij idea 2016.2.1

1.1创建一个gradle项目

在idea中,new -> project -> gradle 创建一个空项目。创建成功后修改build.gradle :

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
group 'com.test'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    
}

根目录下创建.gitignore:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# Created by .ignore support plugin (hsz.mobi)
.idea/
.gradle/
build/
out/
*/build/

1.2 quick start

spring的核心是依赖注入,那么简单的做一个入门测试。

在项目名上右键,new->module->gradle->创建一个java项目quick-start. 修改生产的build.gradle:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
group 'com.test'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'

    compile 'org.springframework:spring-context:4.3.2.RELEASE'
}

这里参考:http://projects.spring.io/spring-framework/#quick-start 的案例.

在quick-start module下创建一个package src/main/java,在java文件夹上右键,Mark Directory as -> Sources Root.

这时候idea的项目配置还没有刷新,需要手动点击一下刷新:

这时候,idea就可以resolve quick-start这个项目以及他的dependency了。

添加spring-context会添加其他依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
dependencies {
    compile 'org.springframework:spring-context:4.3.2.RELEASE'
}

1.2.1 Hello World

我们来创建打印消息的组件。MessagePrinter打印一个MessageService的实例的信息。:

创建接口com.test.hello.MessageService:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test.hello;

/**
 * Created by rmiao on 8/15/2016.
 */
public interface MessageService {
    String getMessage();
}

创建组件com.test.hello.MessagePrinter:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test.hello;

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

/**
 * Created by rmiao on 8/15/2016.
 */
@Component
public class MessagePrinter {

    final private MessageService service;

    @Autowired
    public MessagePrinter(MessageService service){
        this.service = service;
    }

    public void printMessage(){
        System.out.println(this.service.getMessage());
    }
}

@Component声明MessagePrinter是一个bean,由spring容器来管理。

@Autowired 这里是构造器注入,会根据构造器参数的类型和参数名来将spring容器中的bean注入构造器。

针对MessagePrinter的注入参数,我们需要一个MessageService的实现:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
MessageService mockMessageService(){
        return () -> "Hello World!";
}

下面开始启动spring容器来测试这个打印消息组件:

创建com.test.hello.Application:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by rmiao on 8/15/2016.
 */
@Configuration
@ComponentScan
public class Application {

    @Bean
    MessageService mockMessageService(){
        return () -> "Hello World!";
    }

    public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        MessagePrinter printer = context.getBean(MessagePrinter.class);
        printer.printMessage();
    }
}

@Configuration来声明Application是一个配置类,相当于xml配置文件。这里只配置了一个bean mockMessageService.

@Bean 用来声明一个bean并交由spring容器管理。相当于xml配置文件中<bean>. 这种方式表示声明一个MessageService的类的bean,bean id为mockMessageService。

@ComponentScan来声明spring容器扫描范围,这种方式表示扫描Application所在包以及子包下的所有类,然后将识别到的bean放到spring容器中。

AnnotationConfigApplicationContext用来创建spring容器。getBean来获取容器中的bean。

最终,打印Hello World! 

1.2.2 Aop面向切面

spring的另一个强大特性是面向切面编程。可以在任意方法的调用前后进行一些操作。比如记录日志:

添加aop依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
dependencies {

    compile group: 'org.springframework', name: 'spring-aop', version: '4.3.2.RELEASE'
    compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.9'

}

添加logback日志组件依赖:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
dependencies {

    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'
    compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.7'
    compile group: 'ch.qos.logback', name: 'logback-core', version: '1.1.7'
    compile group: 'org.codehaus.groovy', name: 'groovy', version: '2.4.7'

}

在src/main/resources下创建logback.groovy:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy

import static ch.qos.logback.classic.Level.DEBUG
import static ch.qos.logback.classic.Level.INFO

appender("STDOUT", ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5}  - %msg%n"
    }
}
appender("FILE", RollingFileAppender){
    file = "quick-start/log/project.log"
    encoder(PatternLayoutEncoder) {
        pattern = "%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
    }
    rollingPolicy(FixedWindowRollingPolicy) {
        fileNamePattern = "quick-start/log/project.%i.log.zip"
        minIndex = 1
        maxIndex = 10
    }
    triggeringPolicy(SizeBasedTriggeringPolicy) {
        maxFileSize = "2MB"
    }
}

// specify  level
logger("com.test.hello", DEBUG)
//By default, the level of the root level is set to DEBUG
root(DEBUG, ["STDOUT"])

下面开始面相切面编程。

我们想要在消息打印组件的前后做一些工作,但又不想要修改打印组件的内容。那么可以使用@Aspect:

创建:com.test.hello.Monitor.java:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test.hello;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created by rmiao on 8/15/2016.
 */
@Aspect
@Component
public class Monitor {

    private final Logger logger = LoggerFactory.getLogger(Monitor.class);

    @Pointcut("execution(* com.test.hello.MessagePrinter.printMessage())")
    public void  message(){}

    @Before(value = "message()")
    public void pre(){
        logger.info("before print.");
    }

    @After(value = "message()")
    public void after(){
        logger.info("after print.");
    }


}

@Aspect表示这是一个aop切面。等价于xml配置中的<aop>

@Pointcut表示切面的匹配方式

@Before表示切面调用前执行

@After表示切面调用后执行。

要使上述的配置生效,还需开启切面,在配置类中声明@EnableAspectJAutoProxy:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

/**
 * Created by rmiao on 8/15/2016.
 */
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class Application {

    @Bean
    MessageService mockMessageService(){
        return () -> "Hello World!";
    }

    public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        MessagePrinter printer = context.getBean(MessagePrinter.class);
        printer.printMessage();
    }
}

运行:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
八月 15, 2016 9:13:45 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@31cefde0: startup date [Mon Aug 15 21:13:45 CST 2016]; root of context hierarchy
21:13:49.278 [main] INFO  c.t.h.Monitor  - before print.
Hello World!
21:13:49.306 [main] INFO  c.t.h.Monitor  - after print.
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
idea使用maven从0整合ssm+shiro
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
suveng
2019/09/17
1.1K0
idea使用maven从0整合ssm+shiro
Spring源码学习之旅:从理解到实战的深度探索
文章地址:https://cloud.tencent.com/developer/article/2470521
小马哥学JAVA
2024/11/28
1100
Spring Boot 实现日志链路追踪,无需引入组件,让日志定位更方便!
有时候一个业务调用链场景,很长,调了各种各样的方法,看日志的时候,各个接口的日志穿插,确实让人头大。
Java技术栈
2023/02/27
1K0
Spring Boot 实现日志链路追踪,无需引入组件,让日志定位更方便!
阿里3面:Spring声明式事务连环炮,让我措手不及。。
这篇主要介绍声明式事务的用法,我们在工作中基本上用的都是声明式事务,所以这篇文章是比较重要的,建议各位打起精神,正式开始。
路人甲Java
2020/09/14
8990
阿里3面:Spring声明式事务连环炮,让我措手不及。。
Spring日志管理
本博客基于SpringBoot_1.3.6 大家请先简单看下这篇英文的官方文档,文中有说 SpringBoot 内部日志系统使用的是 Commons Logging 并且 SpringBoot 给 JDKLogging , Log4j2(Log4j也是支持的) , Logback 都提供了默认配置,并且如果使用了 Starters ,那么默认使用 Logback 。 那么什么是这个这个 Starters 呢?大家请看我的pom文件:
全栈程序员站长
2022/08/30
1.3K0
Spring日志管理
springboot实战第四章-SpringMVC项目快速搭建
Spring MVC使我们可以简单地开发灵活且松耦合的Web项目,本章将关注基于注解和Java配置的Spring MVC开发。
全栈程序员站长
2021/05/19
7980
使用 Kotlin + Spring Boot 进行后端开发Kotlin示例一:结合 Redis 进行数据存储和查询示例二:结合 RxJava 模拟顺序、并发地执行任务总结
Kotlin 是一个基于 JVM 的编程语言,它的简洁、便利早已不言而喻。Kotlin 能够胜任 Java 做的所有事。目前,我们公司 C 端 的 Android 产品全部采用 Kotlin 编写。公司的后端项目也可能会使用 Kotlin,所以我给他们做一些 demo 进行演示。
fengzhizi715
2018/12/12
1.2K0
Redis整合Spring项目搭建实例
本文介绍了如何使用注解的方式,将Redis缓存整合到你的Spring项目。 首先我们将使用jedis驱动,进而开始配置我们的Gradle。 group 'com.gkatzioura.spring' version '1.0-SNAPSHOT' apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' buildscript { repositories {
CSDN技术头条
2018/02/09
1K0
20201001_kpay支付项目搭建
如何快速的开始一个新项目,最高效的做法是复制一份现有生产环境的项目,修改一下包名称。这样代码是经过考验的,且很多基础功能的代码可以直接复用。
雨粒石
2020/10/10
1.4K0
2.1 Spring5源码--源码编译
  SpringV5.2.7RELEASE+GradleWapper+jdk1.8.0_131编译
用户7798898
2020/09/27
9420
2.1 Spring5源码--源码编译
SpringBoot学习笔记(二)——SpringBoot测试JUnit5、 SpringBoot 配置、Spring IoC与自动装配
Spring Test与JUnit等其他测试框架结合起来,提供了便捷高效的测试手段。而Spring Boot Test 是在Spring Test之上的再次封装,增加了切片测试,增强了mock能力。
张果
2022/05/09
4.2K0
SpringBoot学习笔记(二)——SpringBoot测试JUnit5、 SpringBoot 配置、Spring IoC与自动装配
处理Storm1.2.2 日志报错 与spring boot冲突
通过mvn dependency:tree可以看到Sprint Boot Starter和Storm引入的日志记录框架不相同的,如下:
heasy3
2020/08/03
4040
Spring Boot开发之流水无情(二)
上篇散仙写了一个很简单的入门级的Spring Boot的例子,没啥技术含量,不过,其实学任何东西只要找到第一个突破口,接下来的事情就好办了,人最怕什么? 我想莫过于干一件事情,没有下手的地方了,而当你一旦找到了这感觉,就可以很喜悦的顺藤摸瓜般的探索你强烈想探索求知的某种事物了,这种冥冥之中玄而又玄的感觉是什么?回想一下: (1) 当你把第一个某种编程语言的Hello World的例子,成功的运行在一个IDE中 (2) 当你第一次从老家出发到达了某个你从未涉足过的地方 (3) 当你成功的完成了第一次
我是攻城师
2018/05/11
1K0
Spring基础介绍
在 Spring 1.x 时代,使用 Spring 开发满眼都是 xml 配置的 Bean,随着项目的扩大,我们需要把 xml 配置文件放到不同的配置文件里,那时候需要频繁地在开发的类和配置文件之间切换。
Abalone
2022/07/14
2330
Spring基础介绍
Spring Framework 简介
spring framework 官网:https://projects.spring.io/spring-framework/
全栈程序员站长
2022/09/20
5850
Spring Framework 简介
SpringMVC连接MongoDB操作数据库
缺少关键的beans.xml文件 补上去:注意其中的<mongo:repositories />很重要;
JQ实验室
2022/02/09
4600
Spring Boot - 利用MDC(Mapped Diagnostic Context)实现轻量级同步/异步日志追踪
每日一博 - ThreadLocal VS InheritableThreadLocal VS TransmittableThreadLocal
小小工匠
2024/05/26
2K1
Spring Boot - 利用MDC(Mapped Diagnostic Context)实现轻量级同步/异步日志追踪
Spring Cache抽象-使用Java类注解的方式整合EhCache
Spring Cache抽象-之缓存注解这篇博文中我们介绍了SpringCache抽象注解的使用方式
小小工匠
2021/08/17
3600
【SpringMVC】SpringMVC基础-SpringMVC项目快速搭建、日志框架为logback
Spring MVC提供了一个DispatcherServlet来开发Web应用。
谙忆
2021/01/21
5980
【SpringMVC】SpringMVC基础-SpringMVC项目快速搭建、日志框架为logback
Spring框架核心模块解析与代码示例
在Java开发领域,Spring框架是构建企业级应用的首选框架之一。其核心模块包括Spring Core、Spring Beans、Spring Context、Spring Expression Language(SpEL)以及Spring AOP。这些模块共同构成了Spring框架的基础,为开发人员提供了强大的功能支持。本文将通过代码示例,深入解析Spring框架的核心模块,帮助IT人员更好地理解和运用这一强大的工具。
KPaaS集成扩展
2025/02/06
1250
推荐阅读
相关推荐
idea使用maven从0整合ssm+shiro
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验