“SpringBoot:快速入门”的版本间差异
跳到导航
跳到搜索
(建立内容为“category:SpringBoot”的新页面) |
无编辑摘要 |
||
第1行: | 第1行: | ||
[[category:SpringBoot]] | [[category:SpringBoot]] | ||
== Spring的发展 == | |||
# Spring1.x: | |||
#: 通过'''xml文件'''配置bean:随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。 | |||
# Spring2.x: | |||
#:(JDK 1.5 注解支持)使用'''注解'''对Bean进行申明和注入:大大的减少了xml配置文件,同时也大大简化了项目的开发。 | |||
## 应用的基本配置用xml(如:数据源、资源文件等); | |||
## 业务开发用注解(如:Service中注入bean等); | |||
# Spring3.x(Spring4.x): | |||
#: 推荐使用'''Java配置'''方式:可以完全替代xml配置。 | |||
=== Spring的Java配置方式 === | |||
(Java配置是Spring4.x推荐的配置方式)<br/> | |||
Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的: | |||
# '''@Configuration''':标记类,相当于一个xml配置文件; | |||
# '''@Bean''':标记方法,相当于xml配置中的“<bean>”; | |||
其他配置类注解: | |||
# 读取外部的资源配置文件: | |||
## '''@PropertySource''':指定读取的配置文件; | |||
## '''@Value''':获取配置文件的配置项; | |||
示例:配置数据库连接池: | |||
::<syntaxhighlight lang="java"> | |||
// 通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 | |||
@Configuration | |||
// 配置扫描包,相当于xml中的"<context:component-scan ...>" | |||
@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") | |||
//加载配置文件 | |||
@PropertySource(value = { "classpath:jdbc.properties", "xxx.properties" }, ignoreResourceNotFound = true) | |||
public class SpringConfig { | |||
@Bean | |||
// 通过该注解来表明是一个Bean对象,相当于xml中的<bean> | |||
//1、相当于xml中的<bean>标签 | |||
//2、相当于类中的@Service类的注解 | |||
//所以"UserDAO"可以用于"UserService"属性注入 | |||
public UserDAO getUserDAO() { | |||
return new UserDAO(); // 直接new对象做演示 | |||
} | |||
//返回值,相当于<bean>中的"class"属性 | |||
//方法名称,相当于<bean>中的"id"属性? | |||
// 获取配置文件的配置项 | |||
@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); | |||
// 相应驱动的jdbcUrl | |||
boneCPDataSource.setJdbcUrl(jdbcUrl); | |||
// 数据库的用户名 | |||
boneCPDataSource.setUsername(jdbcUsername); | |||
// 数据库的密码 | |||
boneCPDataSource.setPassword(jdbcUsername); | |||
// 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 | |||
boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60); | |||
// 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 | |||
boneCPDataSource.setIdleMaxAgeInMinutes(30); | |||
// 每个分区最大的连接数 | |||
boneCPDataSource.setMaxConnectionsPerPartition(100); | |||
// 每个分区最小的连接数 | |||
boneCPDataSource.setMinConnectionsPerPartition(5); | |||
return boneCPDataSource; | |||
} | |||
} | |||
</syntaxhighlight> | |||
==== 实例 ==== | |||
# 创建工程以及导入依赖: | |||
#: <syntaxhighlight lang="properties"> | |||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |||
<modelVersion>4.0.0</modelVersion> | |||
<groupId>cn.itcast.springboot</groupId> | |||
<artifactId>itcast-springboot</artifactId> | |||
<version>1.0.0-SNAPSHOT</version> | |||
<packaging>war</packaging> | |||
<dependencies> | |||
<dependency> | |||
<groupId>org.springframework</groupId> | |||
<artifactId>spring-webmvc</artifactId> | |||
<version>4.3.7.RELEASE</version> | |||
</dependency> | |||
<!-- 连接池 --> | |||
<dependency> | |||
<groupId>com.jolbox</groupId> | |||
<artifactId>bonecp-spring</artifactId> | |||
<version>0.8.0.RELEASE</version> | |||
</dependency> | |||
</dependencies> | |||
<build> | |||
<finalName>${project.artifactId}</finalName> | |||
<plugins> | |||
<!-- 资源文件拷贝插件 --> | |||
<plugin> | |||
<groupId>org.apache.maven.plugins</groupId> | |||
<artifactId>maven-resources-plugin</artifactId> | |||
<configuration> | |||
<encoding>UTF-8</encoding> | |||
</configuration> | |||
</plugin> | |||
<!-- java编译插件 --> | |||
<plugin> | |||
<groupId>org.apache.maven.plugins</groupId> | |||
<artifactId>maven-compiler-plugin</artifactId> | |||
<configuration> | |||
<source>1.7</source> | |||
<target>1.7</target> | |||
<encoding>UTF-8</encoding> | |||
</configuration> | |||
</plugin> | |||
</plugins> | |||
<pluginManagement> | |||
<plugins> | |||
<!-- 配置Tomcat插件 --> | |||
<plugin> | |||
<groupId>org.apache.tomcat.maven</groupId> | |||
<artifactId>tomcat7-maven-plugin</artifactId> | |||
<version>2.2</version> | |||
</plugin> | |||
</plugins> | |||
</pluginManagement> | |||
</build> | |||
</project> | |||
</syntaxhighlight> | |||
# 编写User对象: | |||
#: <syntaxhighlight lang="java"> | |||
public class User { | |||
private String username; | |||
private String password; | |||
private Integer age; | |||
// getter & setter & toString | |||
} | |||
</syntaxhighlight> | |||
# 编写UserDao接口: | |||
#: <syntaxhighlight lang="java"> | |||
public interface UserDaoUserDao { | |||
//根据id查询用户信息 | |||
public User findUserById(int id) throws Exception; | |||
} | |||
</syntaxhighlight> | |||
# 编写UserDaoImpl接口:(mybatis) | |||
#: <syntaxhighlight lang="java"> | |||
public class UserDaoImpl implements UserDao { | |||
// 需要向dao实现类中注入SqlSessionFactory | |||
// 这里通过构造方法注入 | |||
private SqlSessionFactory sqlSessionFactory; | |||
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { | |||
this.sqlSessionFactory = sqlSessionFactory; | |||
} | |||
@Override | |||
public User findUserById(int id) throws Exception { | |||
SqlSession sqlSession = sqlSessionFactory.openSession(); | |||
User user = sqlSession.selectOne("test.findUserById", id); | |||
// 释放资源 | |||
sqlSession.close(); | |||
return user; | |||
} | |||
} | |||
</syntaxhighlight> | |||
# 编写UserService实现User数据操作业务逻辑: | |||
#: <syntaxhighlight lang="java"> | |||
@Service | |||
public class UserService { | |||
@Autowired // 注入Spring容器中的bean对象 | |||
private UserDaoImpl UserDaoImpl; | |||
public User findUserById(int id) throws Exception { | |||
// 调用userDAO中的方法进行查询 | |||
return this.UserDaoImpl.findUserById(id); | |||
} | |||
} | |||
</syntaxhighlight> | |||
# 编写SpringConfig用于'''实例化Spring容器''': | |||
#: <syntaxhighlight lang="java" highlight="1-2,5"> | |||
@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 | |||
@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包 | |||
public class SpringConfig { | |||
@Bean // 通过该注解来表明是一个Bean对象,相当于xml中的<bean> | |||
public UserDao getUserDao(){ | |||
return new UserDao(); // 直接new对象做演示 | |||
} | |||
} | |||
</syntaxhighlight> | |||
# 编写测试方法,'''启动Spring容器''': | |||
#: <syntaxhighlight lang="java"> | |||
public class Main { | |||
public static void main(String[] args) { | |||
// 通过Java配置来实例化Spring容器 | |||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); | |||
// 对比使用:使用xml方式的“加载spring配置文件” | |||
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); | |||
// 对比使用:使用xml方式的“根据配置创建对象” | |||
UserService userService = (UserService) context.getBean("userService"); | |||
// 在Spring容器中获取Bean对象 | |||
UserService userService = context.getBean(UserService.class); | |||
// 调用对象中的方法 | |||
List<User> list = userService.queryUserList(); | |||
for (User user : list) { | |||
System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPassword()); | |||
} | |||
// 销毁该容器 | |||
context.destroy(); | |||
} | |||
} | |||
</syntaxhighlight> | |||
* 对比,“xml、注解”于“Java配置类”的实例化Spring容器: | |||
*: <syntaxhighlight lang="java"> | |||
// 通过Java配置来实例化Spring容器 | |||
// 1、Java配置类 | |||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); | |||
// 2、xml、注解 | |||
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); | |||
// 在Spring容器中“获取Bean对象” | |||
// 1、Java配置类 | |||
UserService userService = context.getBean(UserService.class); | |||
// 2、xml、注解 | |||
UserService userService = (UserService) context.getBean("userService"); | |||
</syntaxhighlight> | |||
== Spring Boot == | |||
=== 快速入门 === | |||
== SpringBoot核心 == | |||
== 自动配置的原理 == |
2020年11月2日 (一) 23:26的版本
Spring的发展
- Spring1.x:
- 通过xml文件配置bean:随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。
- Spring2.x:
- (JDK 1.5 注解支持)使用注解对Bean进行申明和注入:大大的减少了xml配置文件,同时也大大简化了项目的开发。
- 应用的基本配置用xml(如:数据源、资源文件等);
- 业务开发用注解(如:Service中注入bean等);
- Spring3.x(Spring4.x):
- 推荐使用Java配置方式:可以完全替代xml配置。
Spring的Java配置方式
(Java配置是Spring4.x推荐的配置方式)
Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的:
- @Configuration:标记类,相当于一个xml配置文件;
- @Bean:标记方法,相当于xml配置中的“<bean>”;
其他配置类注解:
- 读取外部的资源配置文件:
- @PropertySource:指定读取的配置文件;
- @Value:获取配置文件的配置项;
示例:配置数据库连接池:
// 通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 @Configuration // 配置扫描包,相当于xml中的"<context:component-scan ...>" @ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //加载配置文件 @PropertySource(value = { "classpath:jdbc.properties", "xxx.properties" }, ignoreResourceNotFound = true) public class SpringConfig { @Bean // 通过该注解来表明是一个Bean对象,相当于xml中的<bean> //1、相当于xml中的<bean>标签 //2、相当于类中的@Service类的注解 //所以"UserDAO"可以用于"UserService"属性注入 public UserDAO getUserDAO() { return new UserDAO(); // 直接new对象做演示 } //返回值,相当于<bean>中的"class"属性 //方法名称,相当于<bean>中的"id"属性? // 获取配置文件的配置项 @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); // 相应驱动的jdbcUrl boneCPDataSource.setJdbcUrl(jdbcUrl); // 数据库的用户名 boneCPDataSource.setUsername(jdbcUsername); // 数据库的密码 boneCPDataSource.setPassword(jdbcUsername); // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60); // 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 boneCPDataSource.setIdleMaxAgeInMinutes(30); // 每个分区最大的连接数 boneCPDataSource.setMaxConnectionsPerPartition(100); // 每个分区最小的连接数 boneCPDataSource.setMinConnectionsPerPartition(5); return boneCPDataSource; } }
实例
- 创建工程以及导入依赖:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast.springboot</groupId> <artifactId>itcast-springboot</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.jolbox</groupId> <artifactId>bonecp-spring</artifactId> <version>0.8.0.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <!-- 资源文件拷贝插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- java编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> <pluginManagement> <plugins> <!-- 配置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
- 编写User对象:
public class User { private String username; private String password; private Integer age; // getter & setter & toString }
- 编写UserDao接口:
public interface UserDaoUserDao { //根据id查询用户信息 public User findUserById(int id) throws Exception; }
- 编写UserDaoImpl接口:(mybatis)
public class UserDaoImpl implements UserDao { // 需要向dao实现类中注入SqlSessionFactory // 这里通过构造方法注入 private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public User findUserById(int id) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById", id); // 释放资源 sqlSession.close(); return user; } }
- 编写UserService实现User数据操作业务逻辑:
@Service public class UserService { @Autowired // 注入Spring容器中的bean对象 private UserDaoImpl UserDaoImpl; public User findUserById(int id) throws Exception { // 调用userDAO中的方法进行查询 return this.UserDaoImpl.findUserById(id); } }
- 编写SpringConfig用于实例化Spring容器:
@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 @ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包 public class SpringConfig { @Bean // 通过该注解来表明是一个Bean对象,相当于xml中的<bean> public UserDao getUserDao(){ return new UserDao(); // 直接new对象做演示 } }
- 编写测试方法,启动Spring容器:
public class Main { public static void main(String[] args) { // 通过Java配置来实例化Spring容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); // 对比使用:使用xml方式的“加载spring配置文件” ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); // 对比使用:使用xml方式的“根据配置创建对象” UserService userService = (UserService) context.getBean("userService"); // 在Spring容器中获取Bean对象 UserService userService = context.getBean(UserService.class); // 调用对象中的方法 List<User> list = userService.queryUserList(); for (User user : list) { System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPassword()); } // 销毁该容器 context.destroy(); } }
- 对比,“xml、注解”于“Java配置类”的实例化Spring容器:
// 通过Java配置来实例化Spring容器 // 1、Java配置类 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); // 2、xml、注解 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 在Spring容器中“获取Bean对象” // 1、Java配置类 UserService userService = context.getBean(UserService.class); // 2、xml、注解 UserService userService = (UserService) context.getBean("userService");