目录
Spring3.x到Spring4.x再到Spring5.x
添加源代码 创建UserDao ,UserService Bean 对象
@PropertySource加载properties配置文件
八、Freemarker & Thymeleaf视图技术集成
一、学习导图
二、Spring框架发展史
Spring1.x 时代
Spring2.x时代
Spring3.x到Spring4.x再到Spring5.x
Spring 5.X 应用零配置开发
三、注解
声明Bean 注解
注入Bean 注解
Spring5.x 中配置与获取Bean注解
实例1-Ioc中Bean的实例化与获取
创建Spring 普通工程并添加坐标相关配置
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
添加源代码 创建UserDao ,UserService Bean 对象
// UserDao.java
@Repository
public class UserDao {
public void test(){
System.out.println("UserDao.test...");
}
}
// UserService.java
@Service
public class UserService {
@Resource
private UserDao userDao;
public void test(){
System.out.println("UserService.test...");
userDao.test();
}
}
创建IocConfig配置类
// Ioc 容器配置 Java 代码实现
@Configuration
@ComponentScan("com.xxxx.springboot")
public class IocConfig {
}
创建启动类执行测试
public class Starter {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=new
AnnotationConfigApplicationContext(IocConfig.class);
UserService userService= ac.getBean(UserService.class);
userService.test();
}
}
@Bean注解使用
定义AccountDao对象,并交给Spring Ioc 容器进行实例化。
// 注意 此时类级别并未添加 @Repository 注解
public class AccountDao {
public void test(){
System.out.println("AccountDao.test...");
}
}
@Configuration
@ComponentScan("com.xxxx.springboot")
public class IocConfig {
// 返回实例化的单例Bean对象
@Bean
public AccountDao accountDao(){
return new AccountDao();
}
}
@Service
public class UserService {
@Resource
private UserDao userDao;
@Resource
private AccountDao accountDao;
public void test(){
System.out.println("UserService.test...");
userDao.test();
accountDao.test();
}
}
public class Starter {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=new
AnnotationConfigApplicationContext(IocConfig.class);
UserService userService= ac.getBean(UserService.class);
userService.test();
System.out.println(ac.isSingleton("accountDao"));
}
}
实例2-读取外部配置文件
准备properties 配置文件
# user.properties
user.userName=admin
user.password=admin
# jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
@PropertySource加载properties配置文件
@Configuration
@ComponentScan("com.xxx")
@PropertySource(value =
{"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig {
@Value("${jdbc.driver}")
private String url;
@Value("${jdbc.url}")
private String driver;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean
public AccountDao accountDao(){
return new AccountDao();
}
// 控制台打印属性值信息
public void showConfigInfo(){
System.out.println("driver:"+driver+":url:"+url);
System.out.println(":userName:"+userName+":password:"+password);
}
}
其他Bean对象获取properties文件内容
public class UserService {
@Resource
private UserDao userDao;
@Value("${user.userName}")
private String userName;
@Value("${user.password}")
private String userPwd;
public void test(){
System.out.println("UserService.test...");
userDao.test();
System.out.println("userName:"+userName+":password:"+userPwd);
}
}
四、组合注解与元注解
从Spring2开始,为了响应JDK1.5推出的注解功能,Spring开始大量加入注解来替代xml配置。Spring的注解主要用来配置注入Bean,切面相关配置(@Transactional)。随着注解的大量使用,尤其相同的多个注解用到个各类中会很繁琐。这就是所谓的末班代码,是Spring设计原则中要消除的代码。
元注解就是可以注解到别的注解上的注解,被注解的注解称之为组合注解,组合注解具备元注解的功能。Spring本身已经有很多组合注解,比如在定义配置类时用到的 @Configuration 注解就是组合注解,拥有Component 注解功能,即配置类本身也是一个被Ioc维护的单例Bean。
自定义组合注解
定义MyCompScan 注解,拥有@ComponentScan 扫描器注解功能。
/**
* 组合注解MyCompScan 定义
* 拥有元注解@Configuration + @ComponentScan 两者功能
* 覆盖value 属性
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Configuration
@ComponentScan
public @interface MyCompScan {
String[] value() default {}; //复写@ComponentScan的value
}
应用组合注解
@MyCompScan("com.xxxx.springboot")
@PropertySource(value =
{"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig02 {
@Value("${jdbc.driver}")
private String url;
@Value("${jdbc.url}")
private String driver;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean
public AccountDao accountDao(){
return new AccountDao();
}
public void showConfigInfo(){
System.out.println("driver:"+driver+":url:"+url);
System.out.println(":userName:"+userName+":password:"+password);
}
}
public class Starter {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=new
AnnotationConfigApplicationContext(IocConfig02.class);
UserService userService= ac.getBean(UserService.class);
userService.test();
System.out.println(ac.isSingleton("accountDao"));
IocConfig iocConfig=ac.getBean(IocConfig.class);
iocConfig.showConfigInfo();
}
}
五、Spring MVC 零配置创建与部署
创建Spring Mvc Web工程
pom.xml添加坐标相关配置
<!-- spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- web servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<build>
<finalName>springmvc</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.27.v20200227</version>
</plugin>
</plugins>
</build>
@Controller
public class HelloController {
@RequestMapping("/index")
public String index(){
return "index";
}
}
<html>
<head>
<title>Title</title>
</head>
<body>
test web mvc
</body>
</html>
SpringMvc配置类添加
@Configuration
@ComponentScan("com.msb.springboot")
@EnableWebMvc
public class MvcConfig {
@Bean
public InternalResourceViewResolver viewResolver(){ //视图解析器
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// 注册Mvc 配置信息
ctx.register(MvcConfig.class);
// 设置ServletContext 上下文信息
ctx.setServletContext(servletContext);
// 配置转发器Dispatcher
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
// 启动时即实例化Bean
servlet.setLoadOnStartup(1);
}
}
六、Spring Boot 概念&特点
框架概念
框架特点
Spring Boot快速入门
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
@Controller
public class HelloController {
@RequestMapping("hello")
@ResponseBody
public String hello() {
return "hello spring boot";
}
}
@SpringBootApplication
public class StarterApplication
{
public static void main(String[] args) {
SpringApplication.run(Starter.class);
}
}
七、Spring Boot 核心配置
自定义Banner与Banner关闭
@SpringBootApplication
public class StarterApplication {
public static void main(String[] args) {
SpringApplication springApplication=new
SpringApplication(StarterApplication .class);
// 设置banner 图标关闭
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run();
}
}
Spring Boot 配置文件
## 项目启动端口号配置
server.port=8989
## 项目访问上下文路径
server.servlet-path=/mvc
## 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hr?
useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
## 端口号 上下文路径
server:
port: 8989
servlet:
context-path: /mvc
## 数据源配置
spring:
datasource:
type: com.mchange.v2.c3p0.ComboPooledDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/hr
username: root
password: root
Starter 坐标 & 自动化配置
Starter坐标配置
Web starter
使用Spring MVC来构建RESTful Web应用,并使用Tomcat作为默认内嵌容器。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自动化配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!--
父类项目统一对项目依赖版本统一控制!
-->
<version>2.2.2.RELEASE</version>
</parent>
Spring Boot自动化配置
可以看出该注解也是一个组合注解,组合了@Configuration注解,对于Spring Boot应用,
Profile 配置
日志配置
项目中日志信息输出
Starter 启动类中添加Log 日志类,控制台打印日志信息。
package com.xxxx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Starter {
private static Logger logger = LoggerFactory.getLogger(Starter.class);
public static void main(String[] args) {
logger.info("SpringBoot 应用开始启动...");
SpringApplication.run(Starter.class);
}
}
日志输出格式配置
更多日志输出,参考官网
八、Freemarker & Thymeleaf视图技术集成
Freemarker 视图集成
编写IndexController 控制器转发视图
@Controller
public class IndexController {
@RequestMapping("index")
public String index(){
return "index";
}
}
Thymeleaf视图集成
编写IndexController 控制器转发视图
@Controller
public class IndexController {
@RequestMapping("index")
public String index(Model model){
model.addAttribute("msg","hello SpringBoot ");
return "index";
}
}
SpringBoot 静态资源访问
九、SpringBoot应用打包与部署
Jar 包部署
配置打包命令
部署并访问
war包部署
pom.xml修改
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<build>
<!--
配置生成的war文件名
-->
<finalName>springboot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Starter修改
@SpringBootApplication
public class Starter extends SpringBootServletInitializer {
private static Logger logger = LoggerFactory.getLogger(Starter.class);
public static void main(String[] args) {
logger.info("SpringBoot 应用开始启动...");
SpringApplication.run(Starter.class);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
builder) {
return builder.sources(Starter.class);
}
}
部署并访问
十、总结
- 使用 SpringBoot框架的最终目标是简化原生的Spring应用开发带来的繁琐配置,SpringBoot引入的全新的 Starter坐标简化了原有坐标的引入方式,借助SpringBoot的自动化配置让开发者面更加专注业务本身的开发,而不是花费大量的时间来解决配置的问题
- SpringBoot还提供了便捷的环境切换操作,做到不同环境方便快捷的切换,在开发web项目中遇到的视图整合与静态文件的访问操作,更多要归功于SpringBoot本身Starter坐标与自动化配置功能
- SpringBoot打包与部署相比较原有的Maven项目打包与部署简化了很多
其他参考资料