@author Simon
以历代Spring Framework的进步为基础,Spring Boot实现了自动配置,这让Spring能够智能探 测正在构建何种应用程序,自动配置必要的组件以满足应用程序的需要。
英文官网:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
中文官网翻译https://www.breakyizhan.com/springboot/3413.html
Spring Boot提供了一种新的编程范式,能在最小的阻力下开发Spring应用程序。有了它, 你可以更加敏捷地开发Spring应用程序,专注于应用程序的功能,不用在Spring的配置上多花功 夫,甚至完全不用配置。
简单是实现一个springboot的小例子,项目启动输出hello spring boot。首先创建一个maven项目,在pom文件内引入一下内容。
(dependency), 插件(plugins)等装备
org.springframework.boot
spring-boot-starter-parent
1.2.5.RELEASE
junit
junit
3.8.1
test
<!--添加spring-boot-starter-web这个依赖,则纯粹是我们希望构建一个独立运行的web应用而已
(注意, 没有version元素定义,因为spring-boot-starter-parent
已经提供了相应dependencyManagement)。-->
org.springframework.boot
spring-boot-starter-web
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 启动项
*
* @author Simon
*
*/
@SpringBootApplication
public class HelloSpringApplication
{
public static void main(String[] args) throws Exception
{
SpringApplication.run(HelloSpringApplication.class, args);
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* controller
*
* @author Simon
*
*/
@Controller
public class HelloController
{
@RequestMapping("/test")
@ResponseBody
String test()
{
return "hello Spring boot";
}
}
执行HelloSpringApplication.java内的mian()方法,在浏览器上输入http://localhost:8080/test 可以看一输出效果“hello Spring boot ”。
spring-boot模块
spring-boot-starter
spring-boot-starter-amqp
spring-boot-starter-aop
spring-boot-starter-batch
spring-boot-starter-cloud-connectors
spring-boot-starter-data-elasticsearch
spring-boot-starter-data-gemfire
spring-boot-starter-data-jpa
spring-boot-starter-data-mongodb
spring-boot-starter-data-rest
spring-boot-starter-data-solr
spring-boot-starter-freemarker
spring-boot-starter-groovy-templates
spring-boot-starter-hateoas
spring-boot-starter-hornetq
spring-boot-starter-integration
spring-boot-starter-jdbc
spring-boot-starter-jersey
spring-boot-starter-jetty
spring-boot-starter-jta-atomikos
spring-boot-starter-jta-bitronix
spring-boot-starter-logging
spring-boot-starter-log4j
spring-boot-starter-log4j2
spring-boot-starter-mail
spring-boot-starter-mobile
spring-boot-starter-mustache
spring-boot-starter-actuator
spring-boot-starter-parent
spring-boot-starter-redis
spring-boot-starter-security
spring-boot-starter-social-facebook
spring-boot-starter-social-twitter
spring-boot-starter-social-linkedin
spring-boot-starter-remote-shell
spring-boot-starter-test
spring-boot-starter-thymeleaf
spring-boot-starter-tomcat
spring-boot-starter-undertow
spring-boot-starter-velocity
spring-boot-starter-web
spring-boot-starter-websocket
spring-boot-starter-ws
简单了解几个:
默认SpringBoot会给Web应用配备Tomcat作为嵌入式web容器, 如果你不想用默认的tomcat,而想用jetty,那么可以再声明一个对spring-boot-starter-jetty的dependency,之后SpringBoot中使用的EnableAutoConfiguration会施展黑魔法,帮你搞定替换满足你的愿望。
告诉SpringBoot, “给哥使用slf4j和logback!”
连接数据库经过配置文件application.properties进行连接
spring.datasource.url=jdbc:mysql://localhost:3306/db_table?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.primary.url=jdbc:oracle:thin:@127.0.0.1:1521:db_table
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=oracle.jdbc.OracleDriver
@RestController注解相当于@ResponseBody + @Controller合在一起的作用
@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false
@Resource 是JDK1.6支持的注解**,**默认按照名称进行装配
@SpringBootApplication开启了Spring的组件扫描和Spring Boot的自动配置功能。实际上,@SpringBootApplication将三个有用的注解组合在了一起。Spring的@Configuration:标明该类使用Spring基于Java的配置。虽然本书不会写太多配置,但我们会更倾向于使用基于Java而不是XML的配置。
Spring的@ComponentScan:启用组件扫描,这样你写的Web控制器类和其他组件才能被自动发现并注册为Spring应用程序上下文里的Bean。本章稍后会写一个简单的Spring MVC控制器,使用@Controller进行注解,这样组件扫描才能找到它。
Spring Boot 的 @EnableAutoConfiguration :这个不起眼的小注解也可以称为@Abracadabra,就是这一行配置开启了Spring Boot自动配置的魔力,让你不用再写成篇的配置了。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReadingListApplication {
public static void main(String[] args) {
SpringApplication.run(ReadingListApplication.class, args);
}
}
运行指令:mvn spring-boot:run
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit
import readinglist.ReadingListApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration( classes = ReadingListApplication.class)
@WebAppConfiguration
public class ReadingListApplicationTests {
@Test
public void contextLoads() {
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration( classes = ReadingListApplication.class)
@WebAppConfiguration
public class MockMvcWebTests {
@Autowired
private WebApplicationContext webContext;
private MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webContext)
.build();
}
@Test
public void homePage() throws Exception {
mockMvc.perform(get("/readingList"))
.andExpect(status().isOk())
.andExpect(view().name("readingList"))
.andExpect(model().attributeExists("books"))
.andExpect(model().attribute("books", is(empty())));
}
}
需要将 spring-boot-maven-plugin 添加到我们的pom.xml中。在dependencies节点下插入以下内容:
org.springframework.boot
spring-boot-maven-plugin
执行命令
mvn package
mvn install
java –jar
java –jar --server.port=9000
Maven用户可以继承 spring-boot-starter-parent 项目来获取合适的默认设置。该父项目提供以下特性:
默认编译级别为Java 1.8
UTF-8
UTF-8
1.8
###application.properties
server.port=8000
server.port=0//随机端口
//随机内容
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
//配置HTTPS
//文件中提供服务器端口:443,密钥存储文件路径,密钥存储密码,密钥存储类型和密钥别名。如下给出的代码 -
server.port: 443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: springboot
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
@Entity注解表明它是一个JPA实体,id属性加了@Id和@GeneratedValue注解,说明这个字段是实体的唯一标识,并且这个字段的值是自动生成的。
@Configuration 类作为主要源
@ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。
@Import 注解可以用来导入其他配置类
@Configuration 类开始,使用附加的 @ImportResource 注解加载XML配置文件。
@EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一个 @Configuration 类上来选择自动配置。
@Configuration
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })
public class DataSourceAutoConfiguration {
protected static class JdbcTemplateConfiguration {
@Autowired(required = false)
private DataSource dataSource;
@Bean
@ConditionalOnMissingBean(JdbcOperations.class)
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(this.dataSource);
}
}
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
在Spring Boot中使用拦截器,可在以下情况下执行操作 -
要使用拦截器,需要创建支持它的@Component类,它应该实现HandlerInterceptor接口。
以下是在拦截器上工作时应该了解的三种方法
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;
@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle
(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("Pre Handle method is Calling");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Post Handle method is Calling");
}
@Override
public void afterCompletion
(HttpServletRequest request, HttpServletResponse response, Object
handler, Exception exception) throws Exception {
System.out.println("Request and Response is completed");
}
}
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
@Autowired
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor);
}
}
过滤器是用于拦截应用程序的HTTP请求和响应的对象。通过使用过滤器,可以在两个实例上执行两个操作
以下代码显示了带有@Component注解的Servlet过滤器实现类的示例代码。
@Component
public class SimpleFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain)
throws IOException, ServletException {}
@Override
public void init(FilterConfig filterconfig) throws ServletException {}
}
@EnableScheduling放在启动文件上
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;
@Component
public class Scheduler {
//注解用于在特定时间段内触发调度程序。每天上午9:00开始到每天上午9:59结束执行任务
@Scheduled(cron = "0 * 9 * * ?")
//每一秒
@Scheduled(fixedRate = 1000)
//应用程序启动完成3秒后每秒执行一次任务的示例如下所示
@Scheduled(fixedDelay = 1000, initialDelay = 3000)
public void cronJobSch() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Java cron job expression:: " + strDate);
}}
org.springframework.boot
spring-boot-starter-mail
private void sendmail() throws AddressException, MessagingException, IOException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "");
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]", false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
msg.setSubject("Spring Boot Yiibai email");
msg.setContent("Spring Boot Yiibai email", "text/html");
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Spring Boot Yiibai email", "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile("/var/tmp/image19.png");
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
}
web应用都可以使用spring-boot-starter-web模块进行快速搭建和运行。
Spring Boot为内嵌的Tomcat(8和7),Jetty 9和Undertow提供WebSockets自动配置。
需要添加
spring-boot-starter-websocket
模块
以springboot形式实现JTA一共有三种方式,Atomikos ,Bitronix ,Narayana 。
其中Atomikos 是收费产品
Narayana ,目前只有JBoss支持
Bitronix使用spring-boot-starter-jta-bitronixstarter为项目添加合适的Birtronix依赖
https://github.com/bitronix/btm/wiki/Transaction-manager-configuration
权限验证框架,基于springboot进行实现的
https://oauth.net/code/
https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server.git
https://github.com/OAuth-Apis/apis.git
https://github.com/zalando/tokens.git
https://github.com/networknt/light-oauth2.git