spring in action 4th --- quick start

简介:

读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 :

  View Code

根目录下创建.gitignore:

  View Code

 

1.2 quick start

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

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

  View Code

这里参考: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会添加其他依赖:

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

 

1.2.1 Hello World

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

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

复制代码
package com.test.hello;

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

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

复制代码
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的实现:

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

 

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

创建com.test.hello.Application:

复制代码
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依赖:

dependencies {

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

}

添加logback日志组件依赖:

复制代码
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:

  View Code

 

下面开始面相切面编程。

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

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

复制代码
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:

  View Code

 

运行:

八月 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.

 


本文转自Ryan.Miao博客园博客,原文链接:http://www.cnblogs.com/woshimrf/p/5773806.html,如需转载请自行联系原作者

相关文章
|
2月前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
113 7
|
11月前
spring-state-machine的action踩坑
spring-state-machine的action踩坑
99 0
|
Java 应用服务中间件 Spring
运行Spring项目报错 “Web server failed to start. Port 8080 was already in use.”(二)
运行Spring项目报错 “Web server failed to start. Port 8080 was already in use.”(二)
617 0
运行Spring项目报错 “Web server failed to start. Port 8080 was already in use.”(二)
|
Java 应用服务中间件 Spring
运行Spring项目报错“Web server failed to start. Port 8080 was already in use.”(一)
运行Spring项目报错“Web server failed to start. Port 8080 was already in use.”(一)
1476 0
运行Spring项目报错“Web server failed to start. Port 8080 was already in use.”(一)
|
Java 关系型数据库 Spring
struts2+hibernate+spring分页实现(DAO,Service,Action三层架构搭配)
Java代码         import java.util.List;       public interface Pagination {     ...
1008 0
|
30天前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
52 0
|
30天前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
62 0
|
30天前
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
27 0