1、1. 今日大纲 1、 了解Spring的发展 2、 掌握Spring的java配置方式 3、 学习Spring Boot 4、 使用Spring Boot来改造购物车系统 访问 了解更多 2. Spring的发展 2.1. Spring1.x 时代 在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。 2.2. Spring2.x时代 随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml配置文件,同时也
2、大大简化了项目的开发。 那么,问题来了,究竟是应该使用xml还是注解呢? 最佳实践: 1、 应用的基本配置用xml,比如:数据源、资源文件等; 2、 业务开发用注解,比如:Service中注入bean等; 2.3. Spring3.x到Spring4.x 从Spring3.x开始提供了Java配置方式,使用Java配置方式可以更好的理解你配置的Bean,现在我们就处于这个时代,并且Spring4.x和Spring boot都推荐使用java配置的方式。 3. Spring的Java配置方式 Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置。 3.
3、1. @Configuration 和 @Bean
Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的:
1、@Configuration 作用于类上,相当于一个xml配置文件;
2、@Bean 作用于方法上,相当于xml配置中的 4、>4.0.0
5、version>4.3.7.RELEASE
6、
7、s
8、
9、ord; private Integer age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(Stri
10、ng 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
11、 List
12、user);
}
return result;
}
}
3.2.4. 编写UserService 用于实现User数据操作业务逻辑
@Service
public class UserService {
@Autowired // 注入Spring容器中的bean对象
private UserDAO userDAO;
public List
13、DAO.queryUserList();
}
}
3.2.5. 编写SpringConfig 用于实例化Spring容器
@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件
@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包
public class SpringConfig {
@Bean // 通过该注解来表明是一个Bean对象,相当于xml中的
14、tUserDAO(){ return new UserDAO(); // 直接new对象做演示 } } 3.2.6. 编写测试方法 用于启动Spring容器 public class Main { public static void main(String[] args) { // 通过Java配置来实例化Spring容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
15、SpringConfig.class);
// 在Spring容器中获取Bean对象
UserService userService = context.getBean(UserService.class);
// 调用对象中的方法
List
16、me() + ", " + user.getPassword() + ", " + user.getPassword()); } // 销毁该容器 context.destroy(); } } 3.2.7. 测试效果 3.2.8. 小结 从以上的示例中可以看出,使用Java代码就完美的替代xml配置文件,并且结构更加的清晰。 3.3. 实战 3.3.1. 读取外部的资源配置文件 通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法: @Con
17、figuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 @ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包 @PropertySource(value= {"classpath:jdbc.properties"}) public class SpringConfig { @Value("${jdbc.url}") private String jdbcUrl; @Bean // 通过该注解来表明是一个Be
18、an对象,相当于xml中的
19、version>0.8.0.RELEASE
之前的Spring xml配置:
20、rty name="jdbcUrl" value="${jdbc.url}" />
21、"60" />
22、"5" />
23、g jdbcPassword; @Bean(destroyMethod = "close") public DataSource dataSource() { BoneCPDataSource boneCPDataSource = new BoneCPDataSource(); // 数据库驱动 boneCPDataSource.setDriverClass(jdbcDriverClassName); // 相应驱动的jdbcUrl boneCPDataSource.setJdbc
24、Url(jdbcUrl); // 数据库的用户名 boneCPDataSource.setUsername(jdbcUsername); // 数据库的密码 boneCPDataSource.setPassword(jdbcUsername); // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60); // 连接池中未使
25、用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 boneCPDataSource.setIdleMaxAgeInMinutes(30); // 每个分区最大的连接数 boneCPDataSource.setMaxConnectionsPerPartition(100); // 每个分区最小的连接数 boneCPDataSource.setMinConnectionsPerPartition(5); return boneCPDataSource; }
26、
思考: 如何使用该DataSource对象?
4. Spring Boot
4.1. 什么是Spring Boot
4.2. Spring Boot的优缺点
4.3. 快速入门
4.3.1. 设置spring boot的parent
27、boot的项目必须要将parent设置为spring boot的parent,该parent包含了大量默认的配置,大大简化了我们的开发。
4.3.2. 导入spring boot的web支持
28、ot
29、o world!"; } public static void main(String[] args) { SpringApplication.run(HelloApplication.class, args); } } 代码说明: 1、@SpringBootApplication:Spring Boot项目的核心注解,主要目的是开启自动配置。; 2、@Configuration:这是一个配置Spring的配置类; 3、@Controller:标明这是一个SpringMVC的Controller控制器; 4、mai
30、n方法:在main方法中启动一个应用,即:这个应用的入口; 4.3.5. 启动应用 在Spring Boot项目中,启动的方式有两种,一种是直接run Java Application另外一种是通过Spring Boot的Maven插件运行。 第一种: 第二种: 启动效果: 看到如下信息就说明启动成功了: INFO 6188 --- [ main] c.i.springboot.demo.HelloApplication : Started HelloApplication in 3.281 seconds (JVM run
31、ning for 3.601) 4.3.6. 测试 打开浏览器,输入地址: 效果: 是不是很Easy? 4.4. Spring Boot的核心 4.4.1. 入口类和@SpringBootApplication Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序的入口方法。 @SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解: 该注解主要组合了以下注解: 1. @SpringBootConfiguration:这
32、是Spring Boot项目的配置注解,这也是一个组合注解: 在Spring Boot项目中推荐使用@ SpringBootConfiguration替代@Configuration 2. @EnableAutoConfiguration:启用自动配置,该注解会使Spring Boot根据项目中依赖的jar包自动配置项目的配置项: a) 如:我们添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,Spring Boot就会自动配置tomcat和SpringMVC 3. @ComponentScan:默认扫描@SpringBoot
33、Application所在类的同级目录以及它的子目录。 4.4.2. 关闭自动配置 通过上述,我们得知,Spring Boot会根据项目中的jar包依赖,自动做出配置,Spring Boot支持的自动配置如下(非常多): 如果我们不需要Spring Boot自动配置,想关闭某一项的自动配置,该如何设置呢? 比如:我们不想自动配置Redis,想手动配置。 当然了,其他的配置就类似了。 4.4.3. 自定义Banner 启动Spring Boot项目后会看到这样的图案: 这个图片其实是可以自定义的: 1. 打开网站: 2. 拷贝生成的字符到一个文
34、本文件中,并且将该文件命名为banner.txt 3. 将banner.txt拷贝到项目的resources目录中: 4. 重新启动程序,查看效果: 好像没有默认的好看啊!!! 如果不想看到任何的banner,也是可以将其关闭的: 4.4.4. 全局配置文件 Spring Boot项目使用一个全局的配置文件application.properties或者是application.yml,在resources目录下或者类路径下的/config下,一般我们放到resources下。 1、 修改tomcat的端口为8088 重新启动应用,查看效果:
35、2、 修改进入DispatcherServlet的规则为:*.html 测试: 更多的配置: # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # ===========
36、 # ---------------------------------------- # CORE PROPERTIES # ---------------------------------------- # BANNER banner.charset=UTF-8 # Banner . banner.location=classpath:banner.txt # Banner . banner.image.location=classpath:banne
37、r.gif # Banner image (jpg/png can also be used). banner.image.width= # Width of the banner image in chars (default 76) banner.image.height= # Height of the banner image in chars (default based on image height) banner.image.margin= # Left hand image margin in chars (default 2) banner.image.inver
38、t= # If images should be inverted for dark terminal themes (default false) # LOGGING logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions. logging.fil
39、e= # Log . For instance `myapp.log` logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG` logging.path= # Location of the log file. For instance `/var/log` logging.pattern.console= # Appender pattern for output to the console. Only supported with t
40、he default logback setup. logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup. logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup. logging.register-shutdown-hook=false # Re
41、gister a shutdown hook for the logging system when it is initialized. # AOP spring.aop.auto=true # Add @EnableAspectJAutoProxy. spring.aop.proxy-target-class=false # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false). #
42、 IDENTITY (ContextIdApplicationContextInitializer) spring.application.index= # Application index. spring.application.name= # Application name. # ADMIN (SpringApplicationAdminJmxAutoConfiguration) spring.application.admin.enabled=false # Enable admin features for the application. spring.applic
43、ation.admin.jmx-name=org.springframework.boot:type=Admin,name=SpringApplication # JMX name of the application admin MBean. # AUTO-CONFIGURATION spring.autoconfigure.exclude= # Auto-configuration classes to exclude. # SPRING CORE spring.beaninfo.ignore=true # Skip search of BeanInfo classes.
44、 # SPRING CACHE (CacheProperties) spring.cache.cache-names= # Comma-separated list of cache names to create if supported by the underlying cache manager. spring.cache.caffeine.spec= # The spec to use to create caches. Check CaffeineSpec for more details on the spec format. spring.cache.couchbas
45、e.expiration=0 # Entry expiration in milliseconds. By default the entries never expire. spring.cache.ehcache.config= # The location of the configuration use to initialize EhCache. spring.cache.guava.spec= # The spec to use to create caches. Check CacheBuilderSpec for more details on the spec form
46、at. spring.cache.infinispan.config= # The location of the configuration use to initialize Infinispan. spring.cache.jcache.config= # The location of the configuration use to initialize the cache manager. spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation t
47、o use to retrieve the JSR-107 compliant cache manager. Only needed if more than one JSR-107 implementation is available on the classpath. spring.cache.type= # Cache type, auto-detected according to the environment by default. # SPRING CONFIG - using environment property only (Config) spring.con
48、fig.location= # Config . spring.config.name=application # Config . # HAZELCAST (HazelcastProperties) spring.hazelcast.config= # The location of the configuration use to initialize Hazelcast. # PROJECT INFORMATION (ProjectInfoProperties) spring.info.build.location=classpath:META-INF/build-i
49、nfo.properties # Location of the generated build-info.properties file. spring.info.git.location=classpath:git.properties # Location of the generated git.properties file. # JMX spring.jmx.default-domain= # JMX domain name. spring.jmx.enabled=true # Expose management beans to the JMX domain. spring.jmx.server=mbeanServer # MBeanServer bean name. # Email (MailProperties) spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding. spring.mail.host= # SMTP server host. For instance `` spring.mail.jndi-name= # Session JNDI name. When set, takes precedence to other






