Springboot实践

来源:互联网 发布:做淘宝赚钱吗 编辑:程序博客网 时间:2024/06/15 21:45

简介(what)

从Spring 3.x开始,Spring社区的发展方向就是弱化xml配置文件而加大注解的戏份,Spring Boot使用@Configuration、@ComponentScan等注解,省去了大量配置,简化了Spring的开发。个人以为,它Spring之上一个更简洁的框架,适合做提供服务的组件。

优点(Why)

集中式配置(application.properties)+注解,简化开发;
内嵌的Tomcat和Jetty容器,可直接打成jar包启动,无需提供Java war包以及繁琐的Web配置(有jsp的项目也可打可执行war包)
提供了Spring各个插件的基于Maven的pom模板配置,开箱即用;
可以在任何你想自动化配置的地方,实现可能;
提供更多的企业级开发特性,如何系统监控,健康诊断,权限控制;
无冗余代码生成和XML强制配置;
提供支持强大的Restfult风格的编码,非常简洁;

fat jar(jar in jar):生成包含所有依赖jar包的独立可运行的JAR包(可执行jar)

基本使用(how)

前提:使用Gradle或者Maven作为构建工具
引入依赖

<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.3.3.RELEASE</version>    <relativePath/> <!-- lookup parent from repository --></parent>   <!-- Import dependency management from Spring Boot --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>1.3.2.RELEASE</version><exclusions>    <exclusion>        <artifactId>tomcat-embed-core</artifactId>        <groupId>org.apache.tomcat.embed</groupId>    </exclusion></exclusions></dependency>

元素指定该项目作为其子项目,共享其dependencies等。
排除了集成的tomcat,如果使用”import javax.servlet.*;”需要添加以下依赖:

<dependency>        <groupId>org.apache.tomcat</groupId>        <artifactId>tomcat-servlet-api</artifactId>        <version>7.0.42</version>        <!--不打入war包-->        <scope>provided</scope></dependency>

创建启动类

@SpringBootApplication(scanBasePackages = { "com.meituan.ia.workorder" })@ImportResource("classpath:applicationContext.xml")public class WorkOrderBoot {    public static void main(String[] args) {        SpringApplication.run(WorkOrderBoot.class, args);    }}

使用了SpringApplication帮助类,并以Application这个类作为配置来启动Spring的应用上下文。main方法所在的类放在应用包结构的根目录,这样@ComponentScan不用配置任何包路径,便能正常扫描到所有注解(实际应用中,包不唯一,所以还是需要指定scanBasePackages)。
创建Controller

@Controller@RequestMapping(value = "/test")public class TestController {    @RequestMapping(value = "/welcome")    @ResponseBody    public String home() {        return "Hello World!";    }}

同以往的Spring使用。
单元测试

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = SpringBootTestApplication.class)public class SpringBootTestApplicationTests {    @Test    public void contextLoads() {        System.out.println("Hello World");    }}

@SpringApplicationConfiguration指定SpringBoot启动类。当然,也可使用@ContextConfiguration(locations = “classpath:applicationContext.xml”)加载资源。

多样化属性配置
1.命令行启动,带参数
2.application.properties配置:
application.properties:project.name=spring-boot-test
3.applicationContext.xml
注入bean的property
4.@Component类注解@ConfigurationProperties
5.使用@Profile注解,在应用上下文范围,使用@Value(“${project.name}”) 注解获取配置
示例

@Component//@Profile(value="user")@ConfigurationProperties(prefix = "user")public class CommonProperties {    private String name = "name";    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

using

@Controller@RequestMapping(value = "/test")public class TestController {    @Value("${project.name}")    private String projectName; //@Value("${user.name}")    // private String userName;    @Autowired    private CommonProperties properties;    @RequestMapping(value = "/welcome")    @ResponseBody    public String home() {        return "Welcome + " + properties.getGuest() + " to " + projectName;    }} 

使用Spring客户端

下载:spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.zip
配置环境变量
/etc/profile

#springSPRING_HOME=/Users/username/Downloads/software/spring-1.3.0.BUILD-SNAPSHOT PATH=$PATH:$SPRING_HOME/binln -s ./shell-completion/bash/spring /usr/local/bin/spring ln -s ./shell-completion/zsh/_spring /bin/zsh/site-functions/_spring

检查安装:spring –version:
安装完spring客户端,编写代码,即可使用spring命令启动:

//代码甚至无需import@RestControllerclass WebApplication {@RequestMapping("/")String home() {    "Hello World!"    }}
$spring run hello.groovy $spring run hello.groovy -- --server.port=9000 //命令行参数$JAVA_OPTS=-Xmx1024m spring run hello.groovy //带jvm参数

常用注解
@SpringBootApplication由@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解组成。
@Configuration其实是一个@Component注解,可以把由@Configuration注解构成的类当做spring的一个配置的bean。
@EnableAutoConfiguration注解会使spring boot自动配置应用(约定胜于配置),这个自动配置是基于依赖的jar,例如当你在添加spring-boot-starter-web依赖后,classpath会添加tomcat和spring mvc的jar依赖,spring boot会认为你正在开发web应用,则会配置web应用相关的样板式配置,因此,能够快速启动应用及嵌入式容器。
@ConfigurationProperties java类的形式配置,Boot将会识别出它是一个配置对象,并且会按照运行时classpath之中application.properties或application.yml文件中的配置指令填充它的属性。
@ComponentScan注解的功能和xml配置中节点一致,配置组件扫描。
@ImportResource用于导入必要的xml配置。

使用spring boot以war包形式部署或启动

public class HelloWebXml extends SpringBootServletInitializer {    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {        return application.sources(Application.class);    }}

修改pom文件:

<packaging>war</packaging> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions>    <exclusion>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-tomcat</artifactId>    </exclusion></exclusions></dependency><dependency><groupId>org.apache.tomcat</groupId><artifactId>tomcat-servlet-api</artifactId><version>7.0.42</version><!--不打入war包--><scope>provided</scope></dependency> 

运行:java -jar xxx.war
FAQ
Q:省去了web.xml配置,相应功能如何实现?
A:使用@SpringBootApplication(scanBasePackages = { “com.meituan.ia.workorder”}),通过scanBasePackages指定扫描该范围内的所有注入bean。额外的配置,使用@ImportResource(“classpath:applicationContext.xml”),将配置信息加入上下文。
Q:如何定制Listener、Filter,离开了web.xml,如果加载到容器?
A:在自定义过滤器上使用@WebFilter注解,Spring boot应用启动时,自动加载context和filter;Listener同理,使用@WebListener。
方法一:通过Bean配置,在applicationContext装载filter,将其加入filterRegistrationBean,加以配置

<bean id="filterRegistrationBean" class="org.springframework.boot.context.embedded.FilterRegistrationBean">    <property name="filter" ref="myFilter"/>    <property name="urlPatterns">        <list>            <value>/*</value>        </list>    </property></bean><bean id="myFilter" class="com.meituan.ia.filter.MyFilter"></bean>

方法二:写个Component,实现Filter即可

@Componentpublic class MyFilter implements Filter {    public static Logger LOG = LoggerFactory.getLogger(MyFilter.class);    public void init(FilterConfig filterConfig) throws ServletException {    }    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)            throws IOException, ServletException {        LOG.info("------before filter------");        filterChain.doFilter(servletRequest, servletResponse);        LOG.info("------after filter------");    }    public void destroy() {    }}//将其加入FilterRegistrationBean,加以配置@Componentpublic class FilterRegiestration {    @Autowired    private MyFilter myFilter;    @Bean    public FilterRegistrationBean filterRegistrationBean() {        FilterRegistrationBean registration = new FilterRegistrationBean();        registration.setFilter(myFilter);        registration.addUrlPatterns("/**");        registration.addInitParameter("paramName", "paramValue");        registration.setName("myFilter");        return registration;    }}

Listener:自定义listener,实现ServletContextListener,通过ServletListenerRegistrationBean加以配置。

参考文献:
http://projects.spring.io/spring-boot/
http://udn.yyuap.com/doc/Spring-Boot-Reference-Guide/I.%20Spring%20Boot%20Documentation/index.html
http://www.infoq.com/cn/news/2014/01/spring-boot
http://www.infoq.com/cn/articles/microframeworks1-spring-boot/

原创粉丝点击