java xml转对象_现在搞Java还不会SpringBoot?看完这篇两万字笔记精髓就够了

一、大纲

  1. 了解Spring的发展
  2. 掌握Spring的java配置方式
  3. 学习Spring Boot
  4. 使用Spring Boot来改造购物车系统

二、Spring的发展

2.1 Spring1.x 时代

在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。

2.2 Spring2.x时代

随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml配置文件,同时也大大简化了项目的开发。

那么,问题来了,究竟是应该使用xml还是注解呢?

最佳实践:

  1. 应用的基本配置用xml,比如:数据源、资源文件等;
  2. 业务开发用注解,比如:Service中注入bean等;

2.3 Spring3.x到Spring4.x

从Spring3.x开始提供了Java配置方式,使用Java配置方式可以更好的理解你配置的Bean,现在我们就处于这个时代,并且Spring4.x和Spring boot都推荐使用java配置的方式。

三、Spring的Java配置方式

Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置。

3.1 @Configuration 和 @Bean

Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的:

  1. @Configuration 作用于类上,相当于一个xml配置文件;
  2. @Bean 作用于方法上,相当于xml配置中的;

3.2 示例

该示例演示了通过Java配置的方式进行配置Spring,并且实现了Spring IOC功能。

3.2.1 创建工程以及导入依赖

4.0.0cn.itcast.springbootitcast-springboot1.0.0-SNAPSHOTwarorg.springframeworkspring-webmvc4.3.7.RELEASEcom.jolboxbonecp-spring0.8.0.RELEASE${project.artifactId}org.apache.maven.pluginsmaven-resources-pluginUTF-8org.apache.maven.pluginsmaven-compiler-plugin1.71.7UTF-8org.apache.tomcat.maventomcat7-maven-plugin2.2

3.2.2 编写User对象

public class User {private String username;private String password;private Integer age;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}

3.2.3 编写UserDAO 用于模拟与数据库的交互

public class UserDAO {public List queryUserList(){List result = new ArrayList();// 模拟数据库的查询for (int i = 0; i < 10; i++) {User user = new User();user.setUsername("username_" + i);user.setPassword("password_" + i);user.setAge(i + 1);result.add(user);}return result;}}

3.2.4 编写UserService 用于实现User数据操作业务逻辑

@Servicepublic class UserService {@Autowired // 注入Spring容器中的bean对象private UserDAO userDAO;public List queryUserList() {// 调用userDAO中的方法进行查询return this.userDAO.queryUserList();}}

3.2.5 编写SpringConfig 用于实例化Spring容器

@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包public class SpringConfig {@Bean // 通过该注解来表明是一个Bean对象,相当于xml中的public UserDAO getUserDAO(){return new UserDAO();// 直接new对象做演示}}

3.2.6 编写测试方法 用于启动Spring容器

public class Main {public static void main(String[] args) {// 通过Java配置来实例化Spring容器AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);// 在Spring容器中获取Bean对象UserService userService = context.getBean(UserService.class);// 调用对象中的方法List list = userService.queryUserList();for (User user : list) {System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPassword());}// 销毁该容器context.destroy();}}

3.2.7 测试效果

f7ae812bb451699f8847efbbb33ed9b2.png

3.2.8 小结

从以上的示例中可以看出,使用Java代码就完美的替代xml配置文件,并且结构更加的清晰。

3.3 实战

3.3.1 读取外部的资源配置文件

通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法:

@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包@PropertySource(value= {"classpath:jdbc.properties"})public class SpringConfig {@Value("${jdbc.url}")    private String jdbcUrl;@Bean // 通过该注解来表明是一个Bean对象,相当于xml中的public UserDAO getUserDAO(){return new UserDAO();// 直接new对象做演示}}

思考:

①. 如何配置多个配置文件?

b4324a00d71b99b260ca8f20c2d9fb7c.png

②. 如果配置的配置文件不存在会怎么样?

865c8ed62312c37f313b35940fe7acd3.png

3.3.2 配置数据库连接池

导入依赖:

com.jolboxbonecp-spring0.8.0.RELEASE

之前的Spring xml配置:

参考xml配置改造成java配置方式:

@Value("${jdbc.url}")    private String jdbcUrl;@Value("${jdbc.driverClassName}")    private String jdbcDriverClassName;@Value("${jdbc.username}")    private String jdbcUsername;@Value("${jdbc.password}")    private String jdbcPassword;@Bean(destroyMethod = "close")    public DataSource dataSource() {BoneCPDataSource boneCPDataSource = new BoneCPDataSource();// 数据库驱动boneCPDataSource.setDriverClass(jdbcDriverClassName);// 相应驱动的jdbcUrlboneCPDataSource.setJdbcUrl(jdbcUrl);// 数据库的用户名boneCPDataSource.setUsername(jdbcUsername);// 数据库的密码boneCPDataSource.setPassword(jdbcUsername);// 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);// 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0boneCPDataSource.setIdleMaxAgeInMinutes(30);// 每个分区最大的连接数boneCPDataSource.setMaxConnectionsPerPartition(100);// 每个分区最小的连接数    boneCPDataSource.setMinConnectionsPerPartition(5);return boneCPDataSource;}

思考: 如何使用该DataSource对象?

四、Spring Boot

4.1 什么是Spring Boot

随着动态语言的流行(Ruby、Groovy、 Scala、 Node.js),Java 的开发显得格外的笨重:繁多的配置、低下的开发效率、复杂的部署流程以及第三方技术集成难度大。

在上述环境下,Spring Boot应运而生。它使用“习惯优于配置”(项目中存在大量的配置,此外还内置一个习惯性的配置,让你无须手动进行配置)的理念让你的项目快速运行起来。使用SpringBoot很容易创建一个独立运行(运行jar,内嵌Servlet容器)、准生产级别的基于Spring框架的项目,使用Spring Boot你可以不用或者只需要很少的Spring配置。

4.2 Spring Boot的优缺点

优点

  • 快速构建项目;
  • 对主流开发框架的无配置集成;
  • 项目可独立运行,无须外部依赖Servlet容器;
  • 提供运行时的应用监控;
  • 极大地提高了开发、部署效率;
  • 与云计算的天然集成。

缺点

  • 书籍文档较少且不够深入,这是直接促使我写这本书的原因;
  • 如果你不认同Spring框架,这也许是它的缺点,但建议你一定要使用Spring框架。

4.3 快速入门

4.3.1 设置spring boot的parent

org.springframework.bootspring-boot-starter-parent1.5.2.RELEASE

说明:Spring boot的项目必须要将parent设置为spring boot的parent,该parent包含了大量默认的配置,大大简化了我们的开发。

4.3.2 导入spring boot的web支持

org.springframework.bootspring-boot-starter-web

4.3.3 添加Spring boot的插件

org.springframework.bootspring-boot-maven-plugin

4.3.4 编写第一个Spring Boot的应用

@Controller@SpringBootApplication@Configurationpublic class HelloApplication {@RequestMapping("hello")    @ResponseBody    public String hello(){return "hello world!";}public static void main(String[] args) {SpringApplication.run(HelloApplication.class, args);}}

代码说明:

  1. @SpringBootApplication:Spring Boot项目的核心注解,主要目的是开启自动配置。;
  2. @Configuration:这是一个配置Spring的配置类;
  3. @Controller:标明这是一个SpringMVC的Controller控制器;
  4. main方法:在main方法中启动一个应用,即:这个应用的入口;

4.3.5 启动应用

在Spring Boot项目中,启动的方式有两种,一种是直接run Java Application另外一种是通过Spring Boot的Maven插件运行。

第一种:

1b89c0a0cf646c05b3e3e6722195d34f.png

第二种:

2542d74e859314813d75e4c109f2f37c.png

启动效果:

35f1baa90fa315d21078954f24bab406.png

看到如下信息就说明启动成功了:

INFO 6188 --- [           main] c.i.springboot.demo.HelloApplication     : Started HelloApplication in 3.281 seconds (JVM running for 3.601)

4.3.6 测试

打开浏览器,输入地址:

0d2b00faac137e87b0b753de5f4e8b5b.png

效果:

f6d368939ed2d40138a0424067fc38cc.png

是不是很Easy?

4.4 Spring Boot的核心

4.4.41 入口类和@SpringBootApplication

Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序的入口方法。

@SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解:

29d8cfc493caa23025448c9814bf2b65.png

该注解主要组合了以下注解:

①. @SpringBootConfiguration:这是Spring Boot项目的配置注解,这也是一个组合注解:

b09ebc66aa925250486b67a4075a5d68.png

在Spring Boot项目中推荐使用@ SpringBootConfiguration替代@Configuration

②. @EnableAutoConfiguration:启用自动配置,该注解会使Spring Boot根据项目中依赖的jar包自动配置项目的配置项:

a) 如:我们添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,Spring Boot就会自动配置tomcat和SpringMVC

c1addd3e60ba93df2962430c305f0a3f.png

③. @ComponentScan:默认扫描@SpringBootApplication所在类的同级目录以及它的子目录。

4.4.2 关闭自动配置

通过上述,我们得知,Spring Boot会根据项目中的jar包依赖,自动做出配置,Spring Boot支持的自动配置如下(非常多):

965eab3d666b7429745ccfe9bcc0c422.png

如果我们不需要Spring Boot自动配置,想关闭某一项的自动配置,该如何设置呢?

比如:我们不想自动配置Redis,想手动配置。

a8caf92dd51d1e3eb54562402d6cee64.png

当然了,其他的配置就类似了。

4.4.3 自定义Banner

启动Spring Boot项目后会看到这样的图案:

2b1382ffed30b8cb8934cf749ce31de7.png

这个图片其实是可以自定义的:

①. 打开网站:http://patorjk.com/software/taag/#p=display&h=3&v=3&f=4Max&t=itcast Spring Boot

b09272fd049a9ee0d2a43af158f8b7eb.png

②. 拷贝生成的字符到一个文本文件中,并且将该文件命名为banner.txt

③. 将banner.txt拷贝到项目的resources目录中:

3d5cb29269ff1b32f46772af91379337.png

④. 重新启动程序,查看效果:

cdd4cb0b24b46d3e1d280d4a2a465df1.png

好像没有默认的好看啊!!!

如果不想看到任何的banner,也是可以将其关闭的:

2fa863c02fa7aa45d3faaeb3b66a7091.png

4.4.4 全局配置文件

Spring Boot项目使用一个全局的配置文件application.properties或者是application.yml,在resources目录下或者类路径下的/config下,一般我们放到resources下。

①. 修改tomcat的端口为8088

7d92456be0f1d75465364b4e2237edfc.png

重新启动应用,查看效果:

06b21ec724beadda26201ad73d72cec4.png

②. 修改进入DispatcherServlet的规则为:*.html

0df7c26a843bf1326a19ce70cd890876.png

测试:

8cae81c5b42613621d391babf40bb620.png
185fa2db0fb20a8b940ac9b2f22b3406.png

4.4.5 Starter pom

Spring Boot为我们提供了简化企业级开发绝大多数场景的sarter pom,只要使用了应用场景所需要的sater pom,相关的技术配置将会消除,就可以得到Sprig Boot为我们提供的自动配置的Bean。

b4a7dce7536c36f563ebb860dacfd811.png

4.4.6 Xml 配置文件

Spring Boot 提倡零配置,即无xml配置,但是在实际项目中,可能有一些特殊要求你必须使用xml配置,这时我们可以通过Spring提供的@ImportResource来加载xml配置,例如:

CImportResource({"clas spath: some-context. xml" ,"classpath: another-context. xml"})

4.4.7 日志

Spring Boot对各种日志框架都做了支持,我们可以通过配置来修改默认的日志的配置:

#设置日志级别logging.level.org.springframework=DEBUG

格式:

logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`

4.5 Spring Boot的自动配置的原理

Spring Boot在进行SpringApplication对象实例化时会加载META-INF/spring.factories文件,将该配置文件中的配置载入到Spring容器。

4.5.1 Maven下载源码

通过 dependency:sources 该命令可以下载该项目中所有的依赖的包的源码。

4.5.2 源码分析

org.springframework.boot.SpringApplication:

cec8e74c084fe7047a287c27cc06c7b5.png
57c3218d3eb282cca1e40e30947eb946.png

org.springframework.core.io.support.SpringFactoriesLoader:

ec3428a7109cbf634e05e0a945011326.png
333566b972e5e3ffb81ab84530979cfb.png

由此可见,读取该配置文件来加载内容。

4.5.3 举例:Redis的自动配置

从上述的配置中可以看出,org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration是Redis的自动配置。

内容:

92ba61ff3db9cc4c020c1cdddc2f482e.png
6f645777f7c816428eb9e41082768662.png

4.5.4 条件注解

  • @ConditionalOnBean:当容器里有指定的Bean的条件下
  • @ConditionalOnClass:当类路径下有指定的类的条件下。
  • @ConditionalOnExpression: 基于SpEL表达式作为判断条件。
  • @ConditionalOnJava:基于JVM版本作为判断条件。
  • @ConditionalOnJndi:在JNDI存在的条件下查找指定的位置。
  • @ConditionalOnMissingBean:当容器里没有指定Bean的情况下。
  • @ConditionalOnMissingClass:当类路径下没有指定的类的条件下。
  • @ConditionalOnNotWebApplication:当前项目不是Web项目的条件下。
  • @ConditionalOnProperty:指定的属性是否有指定的值。
  • @ConditionalOnResource:类路径是否有指定的值。
  • @ConditionalOnSingleCandidate:当指定Bean 在容器中只有一个,或者虽然有多个但是指定首选的Bean。
  • @ConditionalOn WebA pplication:当前项目是Web项目的条件下

五、Spring Boot的web开发

Web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration

5.1 自动配置的ViewResolver

a5790eeb49ec47ae04754061e42ad6dd.png

视图的配置mvcProperties对象中:

org.springframework.boot.autoconfigure.web.WebMvcProperties.View

4548c3d35aa5c42aa49e84bbc889b274.png

5.2 自动配置静态资源

5.2.1 进入规则为 /

如果进入SpringMVC的规则为/时,Spring Boot的默认静态资源的路径为: spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

测试:

71017a0a3d6cefb271024fdcef743505.png
2a25e82d68447bf6ae603e478674ccdc.png
b2b9ead0119b245b80f560aaa3b765d5.png

5.2.2. 进入规则为*.xxx 或者 不指定静态文件路径时 将静态资源放置到webapp下的static目录中即可通过地址访问:

e961826606e02d947be941e212e5edd5.png

测试:

3ccef1ffb2ef78532ab2fcaef7c661f0.png

5.3 自定义消息转化器

自定义消息转化器,只需要在@Configuration的类中添加消息转化器的@bean加入到Spring容器,就会被Spring Boot自动加入到容器中。

@Bean    public StringHttpMessageConverter stringHttpMessageConverter(){StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));return converter;}

默认配置:

c6e809da7ad09102cda92ccca163cb3a.png
8e39114986eed9282db3b8e9e3f8c836.png

5.4 自定义SpringMVC的配置

有些时候我们需要自已配置SpringMVC而不是采用默认,比如说增加一个拦截器,这个时候就得通过继承WebMvcConfigurerAdapter然后重写父类中的方法进行扩展。

import java.nio.charset.Charset;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.context.annotation.Configuration;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.http.converter.StringHttpMessageConverter;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration //申明这是一个配置public class MySrpingMVCConfig extends WebMvcConfigurerAdapter{// 自定义拦截器@Override    public void addInterceptors(InterceptorRegistry registry) {HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {@Override            public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)                    throws Exception {System.out.println("自定义拦截器............");return true;}@Override            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,                    ModelAndView modelAndView) throws Exception {}@Override            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,                    Exception ex) throws Exception {}};registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");}// 自定义消息转化器的第二种方法@Override    public void configureMessageConverters(List> converters) {StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));converters.add(converter);}}

六、改造购物车系统

6.1 创建购物车的Spring Boot工程

73ba71b166d366918f8c78a8f1867736.png

6.2 导入依赖

4.0.0org.springframework.bootspring-boot-starter-parent1.5.2.RELEASEcom.taotao.carttaotao-cart-springboot1.0.0-SNAPSHOTwarcom.taotao.commontaotao-common1.0.0-SNAPSHOTcom.taotao.ssotaotao-sso-interface1.0.0-SNAPSHOTjunitjunittestorg.springframeworkspring-jdbcorg.springframeworkspring-aspectsorg.springframework.bootspring-boot-starter-weborg.mybatismybatis3.2.8org.mybatismybatis-spring1.2.2com.github.pagehelperpagehelper3.7.5com.github.jsqlparserjsqlparser0.9.1com.github.abel533mapper2.3.4mysqlmysql-connector-javaorg.slf4jslf4j-log4j12com.jolboxbonecp-spring0.8.0.RELEASEorg.apache.httpcomponentshttpclientjstljstl1.2org.apache.commonscommons-lang33.3.2org.apache.commonscommons-io1.3.2commons-codeccommons-codecorg.springframework.amqpspring-rabbit1.4.0.RELEASEcom.alibabadubbo2.5.3springorg.springframeworkorg.apache.zookeeperzookeeper3.3.3com.github.sgroschupfzkclient0.1org.apache.maven.pluginsmaven-resources-pluginUTF-8org.apache.maven.pluginsmaven-compiler-plugin1.71.7UTF-8org.springframework.bootspring-boot-maven-plugin

6.3 将taotao-cart中的java代码拷贝到taotao-car-springboot

a1f2f3c8e42098a80f0ac1f060fc81a4.png

拷贝完成后:

6ac426784dd71fc3d361b8196491a96d.png

并且将properties文件也拷贝过来:

1de48fc007216eb59822f63507d529d3.png

将页面也拷贝过来:

831b2487633fde02b818f7b64f682f3e.png

6.3.1 编写Spring配置类TaotaoApplication

43b59eceb02f4f0ed537eb9c2738a8f3.png

6.3.2 设置tomcat端口

application.properties:

ea2c00c8203af6da43aa040e0281a5ca.png

6.3.3 读取外部的配置文件

@Configuration@PropertySource(value = { "classpath:jdbc.properties", "classpath:env.properties",        "classpath:httpclient.properties", "classpath:redis.properties", "classpath:rabbitmq.properties" }, ignoreResourceNotFound = true)public class TaotaoApplication {}

6.3.4 设置扫描包

4ee06760268e4568bdec774dbde9a104.png

6.3.5 定义数据源

@Value("${jdbc.url}")    private String jdbcUrl;@Value("${jdbc.driverClassName}")    private String jdbcDriverClassName;@Value("${jdbc.username}")    private String jdbcUsername;@Value("${jdbc.password}")    private String jdbcPassword;@Bean(destroyMethod = "close")    public DataSource dataSource() {BoneCPDataSource boneCPDataSource = new BoneCPDataSource();// 数据库驱动boneCPDataSource.setDriverClass(jdbcDriverClassName);// 相应驱动的jdbcUrlboneCPDataSource.setJdbcUrl(jdbcUrl);// 数据库的用户名boneCPDataSource.setUsername(jdbcUsername);// 数据库的密码boneCPDataSource.setPassword(jdbcUsername);// 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);// 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0boneCPDataSource.setIdleMaxAgeInMinutes(30);// 每个分区最大的连接数boneCPDataSource.setMaxConnectionsPerPartition(100);// 每个分区最小的连接数boneCPDataSource.setMinConnectionsPerPartition(5);return boneCPDataSource;}

6.3.6 设置Mybatis和Spring Boot整合

Mybatis和Spring Boot的整合有两种方式:

  • 第一种:使用mybatis官方提供的Spring Boot整合包实现,地址:https://github.com/mybatis/spring-boot-starter
  • 第二种:使用mybatis-spring整合的方式,也就是我们传统的方式

这里我们推荐使用第二种,因为这样我们可以很方便的控制Mybatis的各种配置。

首先,创建一个Mybatis的配置类:

b2d46b14ec94b8d49a0eccafbda10ec4.png

代码:

import javax.sql.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;@Configurationpublic class MyBatisConfig {@Bean    @ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();// 设置数据源sqlSessionFactoryBean.setDataSource(dataSource);// 设置mybatis的主配置文件ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);// 设置别名包sqlSessionFactoryBean.setTypeAliasesPackage("com.taotao.cart.pojo");return sqlSessionFactoryBean;}}

然后,创建Mapper接口的扫描类MapperScannerConfig:

b10aacc2e42bafc0668c56b085f7e81f.png

代码:

import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration@AutoConfigureAfter(MyBatisConfig.class) //保证在MyBatisConfig实例化之后再实例化该类public class MapperScannerConfig {// mapper接口的扫描器@Bean    public MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.taotao.cart.mapper");return mapperScannerConfigurer;}}

6.3.7 设置事务管理

在Spring Boot中推荐使用@Transactional注解来申明事务。

首先需要导入依赖:

org.springframework.bootspring-boot-starter-jdbc

当引入jdbc依赖之后,Spring Boot会自动默认分别注入DataSourceTransactionManager或JpaTransactionManager,所以我们不需要任何额外配置就可以用@Transactional注解进行事务的使用。

在Service中添加@Transactional注解:

d87c65caf8e6b643e70a37b782a6b9ae.png

@Transactional不仅可以注解在方法上,也可以注解在类上。当注解在类上的时候意味着此类的所有public方法都是开启事务的。如果类级别和方法级别同时使用了@Transactional注解,则使用在类级别的注解会重载方法级别的注解。

6.3.8 设置Redis和Spring的整合

在Spring Boot中提供了RedisTempplate的操作,我们暂时不做学习,先按照我们之前的实现来完成。

代码:

import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import redis.clients.jedis.JedisPoolConfig;import redis.clients.jedis.JedisShardInfo;import redis.clients.jedis.ShardedJedisPool;@Configuration@PropertySource(value = "classpath:redis.properties")public class RedisSpringConfig {@Value("${redis.maxTotal}")    private Integer redisMaxTotal;@Value("${redis.node1.host}")    private String redisNode1Host;@Value("${redis.node1.port}")    private Integer redisNode1Port;private JedisPoolConfig jedisPoolConfig() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxTotal(redisMaxTotal);return jedisPoolConfig;}@Bean    public ShardedJedisPool shardedJedisPool() {List jedisShardInfos = new ArrayList();jedisShardInfos.add(new JedisShardInfo(redisNode1Host, redisNode1Port));return new ShardedJedisPool(jedisPoolConfig(), jedisShardInfos);}}

6.3.9 设置Httpclient和Spring的整合

import org.apache.http.client.config.RequestConfig;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.context.annotation.Scope;import com.taotao.common.httpclient.IdleConnectionEvictor;@Configuration@PropertySource(value = "classpath:httpclient.properties")public class HttpclientSpringConfig {@Value("${http.maxTotal}")    private Integer httpMaxTotal;@Value("${http.defaultMaxPerRoute}")    private Integer httpDefaultMaxPerRoute;@Value("${http.connectTimeout}")    private Integer httpConnectTimeout;@Value("${http.connectionRequestTimeout}")    private Integer httpConnectionRequestTimeout;@Value("${http.socketTimeout}")    private Integer httpSocketTimeout;@Value("${http.staleConnectionCheckEnabled}")    private Boolean httpStaleConnectionCheckEnabled;@Autowired    private PoolingHttpClientConnectionManager manager;@Bean    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();// 最大连接数poolingHttpClientConnectionManager.setMaxTotal(httpMaxTotal);// 每个主机的最大并发数poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpDefaultMaxPerRoute);return poolingHttpClientConnectionManager;}// 定期关闭无效连接@Bean    public IdleConnectionEvictor idleConnectionEvictor() {return new IdleConnectionEvictor(manager);}// 定义Httpclient对@Bean    @Scope("prototype")    public CloseableHttpClient closeableHttpClient() {return HttpClients.custom().setConnectionManager(this.manager).build();}// 请求配置@Bean    public RequestConfig requestConfig() {return RequestConfig.custom().setConnectTimeout(httpConnectTimeout) // 创建连接的最长时间.setConnectionRequestTimeout(httpConnectionRequestTimeout) // 从连接池中获取到连接的最长时间.setSocketTimeout(httpSocketTimeout) // 数据传输的最长时间.setStaleConnectionCheckEnabled(httpStaleConnectionCheckEnabled) // 提交请求前测试连接是否可用.build();}}

6.3.10 设置RabbitMQ和Spring的整合

我们之前使用的Spring-Rabbit的xml方式,现在我们要改造成java方式,并且Spring Boot对RabbitMQ的使用做了自动配置,更加的简化了我们的使用。

①. 在导入spring-boot-starter-amqp的依赖;

20bc93fd079b9c96174fb28609bed3f0.png

②. 在application.properties文件中配置RabbitMQ的连接信息

b01ccfdf72dfcf9601c53df227e4f282.png

③. 编写Rabbit的Spring配置类

import org.springframework.amqp.core.Queue;import org.springframework.amqp.rabbit.connection.ConnectionFactory;import org.springframework.amqp.rabbit.core.RabbitAdmin;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class RabbitMQSpringConfig {@Autowired    private ConnectionFactory connectionFactory;// 管理@Bean    public RabbitAdmin rabbitAdmin() {return new RabbitAdmin(connectionFactory);}// 声明队列@Bean    public Queue taotaoCartLoginQueue() {// 默认就是自动声明的return new Queue("TAOTAO-CART-LOGIN-QUEUE", true);}// 声明队列@Bean    public Queue taotaoCartOrderSuccessQueue() {// 默认就是自动声明的return new Queue("TAOTAO-CART-ORDER-SUCCESS-QUEUE", true);}}

④. 设置监听

2542a2e184aba2cdb475df3519b6d44a.png
a76692ec56117c74f4e2979064183659.png

6.3.11 设置SpringMVC的配置

原有配置:

5cf87f3757f1293d86aa323a01bb26d1.png

具体实现: 视图解析器配置:

62c897d309cbf56f4159caa3a28204e9.png

自定义拦截器:

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import com.taotao.cart.interceptors.UserLoginHandlerInterceptor;@Configurationpublic class SpringMVCConfig extends WebMvcConfigurerAdapter {@Override    public void addInterceptors(InterceptorRegistry registry) {// 判断用户是否登录的拦截器registry.addInterceptor(new UserLoginHandlerInterceptor()).addPathPatterns("/cart/**");}}

6.3.12 设置dubbo的配置

Dubbo目前只能使用xml配置的方式,所以我们需要保留xml,并且需要将该xml加入到现有的Spring容器中才能生效。

①. 将dubbo目录以及下面的xml配置文件拷贝到taotao-cat-springboot中

83fede900562aa2994de16c97bb64afd.png

②. 将dubbo的xml文件加入到spring容器

108245ae7e854a3e0f256fa96891a5cc.png

6.4 编写入口类

4d4d38f43bfc7e2d2ad2961908f11405.png

编写main方法:

f1b3fad2fa5394d9a3aee9ccb6ab0356.png

6.4.1 启动错误1

关键错误(丢失了web容器的工厂,也就是说我们并没有把它作为一个web应用来启动):

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.

解决:

0e1e6fc768500a61bf412e9f17e61e87.png

让Spring Boot来自动选择并且完成web的相关加载工作。

6.4.2 Slf4j日志警告

eb308d09bb44a298ea8fa66822c2594a.png

提示我们当前的项目中slf4j引入了2个,导致了jar冲突。

解决:

①. 删除自己引入到slf4j的依赖

aea1bead542cc03d2c22abd027945b95.png

②. 将taotao-common中传递的依赖排除掉

a74fe287756a2a44fc06e9ec86fc0265.png
ae459d00b6836b9c56d6c15ce49a593d.png

再次启动,发现警告没了:

ca36ad9b3b026aa1424fcffd6730b5c0.png

6.4.3 解决jsp访问404的问题

由于Spring boot使用的内嵌的tomcat,而内嵌的tamcat是不支持jsp页面的,所有需要导入额外的包才能解决。

org.apache.tomcat.embedtomcat-embed-jasperprovided

重新启动进行测试:

22fc2bdebc687c3ff7200fb41f534756.png

6.4.4 拦截器中的UserService空指针异常

分析:由于添加拦截器时,直接对UserLoginHandlerInterceptor进行new操作,导致UserService无法注入,所以有空指针异常。

解决:

1e2937fa5396fba000e3a38269b32383.png
5f37847cb7d08d9e6fad7e70a629897f.png

6.4.5 路径问题

现在我们进入Servlet的路径为”/”,访问*.html页面没问题,但是,访问 /service/* 就会有问题,所以需要改一下js,将原有的/service/ 改为 /

d4f21d17b76a60fc4494e6e2b500e22d.png

测试,功能一切ok。

七、发布到独立的tomcat中运行

在开发阶段我们推荐使用内嵌的tomcat进行开发,因为这样会方便很多,但是到生成环境,我希望在独立的tomcat容器中运行,因为我们需要对tomcat做额外的优化,这时我们需要将工程打包成war包发进行发布。

7.1 工程的打包方式为war

caa38d9d487776ee84f111db20b0abbb.png

7.2 将spring-boot-starter-tomcat的范围设置为provided

设置为provided是在打包时会将该包排除,因为要放到独立的tomcat中运行,是不需要的。

org.springframework.bootspring-boot-starter-tomcatprovided

7.3 修改代码,设置启动配置

需要集成SpringBootServletInitializer,然后重写configure,将Spring Boot的入口类设置进去。

33b7bae73e5d221f33877529b9200ce6.png

7.4 打war包

5f8b42c262bc60b33575db142d45ef7a.png

打包成功:

3848d096896179b906015079310c6fac.png

7.5 部署到tomcat

解压apache-tomcat-7.0.57.tar.gz,将war包解压到webapps下的ROOT目录中,启动:

a624e012a72d06537a9111b747739df3.png
afd3d4874b2eff4cf5471f68f5e8eb5c.png
7d93a87f337ae677f66034fe415449f1.png

写在最后:

  • 针对于Java程序员,笔者最近整理了一些面试真题,思维导图,程序人生等PDF学习资料;
  • 关注私信我"86",即可获取!
  • 希望读到这的您能点个小赞和关注下我,以后还会更新技术干货,谢谢您的支持!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值