大家好,又见面了,我是你们的朋友全栈君。
@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。 @ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。 @Configuration 等同于spring的XML配置文件;使用Java代码可以检查类型安全。 @EnableAutoConfiguration 自动配置。 @ComponentScan 组件扫描,可自动发现和装配一些Bean。 @Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务。 @RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直 接填入HTTP响应体中,是REST风格的控制器。 @Autowired自动导入。 @PathVariable获取参数。 @JsonBackReference解决嵌套外链问题。 @RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RequestMapping(“/test”)
@ResponseBody
public String test(){
return”ok”;
}
@Controller
@RequestMapping(“/demoInfo”)
publicclass DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
//会使用hello.html或者hello.ftl模板进行渲染显示.
return"/hello";
}
}
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return"ok";
}
@Value(value = “#{
message}”)
private String message;
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
@Entity:@Table(name=”“):表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略 @MappedSuperClass:用在确定是父类的entity上。父类的属性子类可以继承。 @NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。 @Column:如果字段名与列名相同,则可以省略。 @Id:表示该属性为主键。 @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。 @SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name为sequence的名称,以便使用,sequenceName为数据库的sequence名称,两个名称可以一致。 @Transient:表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。@Basic(fetch=FetchType.LAZY):标记可以指定实体属性的加载方式 @JsonIgnore:作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。 @JoinColumn(name=”loginId”):一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。 @OneToOne、@OneToMany、@ManyToOne:对应hibernate配置文件中的一对一,一对多,多对一。
@RequestMapping:@RequestMapping(“/path”)表示该控制器处理所有“/path”的UR L请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解有六个属性: params:指定request中必须包含某些参数值是,才让该方法处理。 headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。 value:指定请求的实际地址,指定的地址可以是URI Template 模式 method:指定请求的method类型, GET、POST、PUT、DELETE等 consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html; produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回@RequestParam:用在方法的参数前面。
@RequestParam
String a =request.getParameter(“a”)。
@PathVariable:路径变量。如
RequestMapping(“user/get/mac/{
macAddress}”)
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}
参数与大括号里的名字一样要相同。
@ControllerAdvice:包含@Component。可以被扫描到。统一处理异常。 @ExceptionHandler(Exception.class):用在方法上面表示遇到这个异常就执行以下方法。
方法的标注: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad 。 它们标注在某个方法之前,没有任何参数。这些标注下的方法在实体的状态改变前后时进行调用,相当于拦截器; pre 表示在状态切换前触发,post 则表示在切换后触发。 @PostLoad 事件在下列情况触发:
当你在执行各种持久化方法的时候,实体的状态会随之改变,状态的改变会引发不同的生命周期事件。这些事件可以使用不同的注释符来指示发生时的回调函数。 @javax.persistence.PostLoad:加载后。 @javax.persistence.PrePersist:持久化前。 @javax.persistence.PostPersist:持久化后。 @javax.persistence.PreUpdate:更新前。 @javax.persistence.PostUpdate:更新后。 @javax.persistence.PreRemove:删除前。 @javax.persistence.PostRemove:删除后。
package com.test.spring.support.configuration;
@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
}
}
相当于:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>
主方法进行测试:
package com.test.spring.support.configuration;
public class TestMain {
public static void main(String[] args) {
//@Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//如果加载spring-context.xml文件:
//ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
}
}
从运行主方法结果的控制台可以看出,spring容器已经启动了:
八月 11, 2016 12:04:11 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@203e25d3: startup date [Thu Aug 11 12:04:11 CST 2016]; root of context hierarchy
spring容器启动初始化。。。
package com.test.spring.support.configuration;
public class TestBean {
public void sayHello(){
System.out.println("TestBean sayHello...");
}
public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
public void start(){
System.out.println("TestBean 初始化。。。");
}
public void cleanUp(){
System.out.println("TestBean 销毁。。。");
}
}
配置类:
package com.test.spring.support.configuration;
@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
}
//@Bean注解注册bean,同时可以指定初始化和销毁方法
//@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}
主方法测试类:
package com.test.spring.support.configuration;
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//获取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}
注: (1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; (2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; (3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。 bean类:
package com.test.spring.support.configuration;
//添加注册bean的注解
@Component
public class TestBean {
public void sayHello(){
System.out.println("TestBean sayHello...");
}
public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
}
配置类:
//开启注解配置
@Configuration
//添加自动扫描注解,basePackages为TestBean包路径
@ComponentScan(basePackages = "com.test.spring.support.configuration")
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器启动初始化。。。");
}
//取消@Bean注解注册bean的方式
//@Bean
//@Scope("prototype")
//public TestBean testBean() {
// return new TestBean();
//}
}
主方法测试获取bean对象:
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//获取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}
sayHello()方法都被正常调用。
<beans>
<bean id="orderService" class="com.acme.OrderService"/>
<constructor-arg ref="orderRepository"/>
</bean>
<bean id="orderRepository" class="com.acme.OrderRepository"/>
<constructor-arg ref="dataSource"/>
</bean>
</beans>
使用bean:
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
OrderService orderService = (OrderService) ctx.getBean("orderService");
现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:
@Configuration
public class ApplicationConfig {
public @Bean OrderService orderService() {
return new OrderService(orderRepository());
}
public @Bean OrderRepository orderRepository() {
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource() {
// instantiate and return an new DataSource …
}
}
使用bean:
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
OrderService orderService = ctx.getBean(OrderService.class);
这么做的好处 1.使用纯java代码,不在需要xml。 2.在配置中也可享受OO带来的好处(面向对象)。 3.类型安全对重构也能提供良好的支持。 4.减少复杂配置文件的同时依旧能享受到所有springIoC容器提供的功能。
@Service: 注解在类上,表示这是一个业务层bean @Controller:注解在类上,表示这是一个控制层bean @Repository: 注解在类上,表示这是一个数据访问层bean @Component: 注解在类上,表示通用bean ,value不写默认就是类名首字母小写 @Autowired:按类型注入.默认属性required= true;当不能确定 Spring 容器中一定拥有某个类的Bean 时, 可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false), 这等于告诉Spring:在找不到匹配Bean时也不抛出BeanCreationException 异常。@Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变byName 了。@Autowired可以对成员变量、方法以及构造函数进行注释,而 @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同,所以 Spring 不将 @Autowired 和 @Qualifier 统一成一个注释类。 @Resource: 按名称装配
缺点 Spring Boot作为一个微框架,离微服务的实现还是有距离的。springboot 只是为了提高开发效率,是为了提升生产力的。 没有提供相应的服务发现和注册的配套功能,自身的acturator所提供的监控功能,也需要与现有的监控对接。没有配套的安全管控方案,对于REST的落地,还需要自行结合实际进行URI的规范化工作。 注意: 将现有或传统的Spring Framework项目转换为Spring Boot应用程序是一个非常困难和耗时的过程。它仅适用于全新Spring项目。
package com.xuliugen.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
(3)提供starter简化Manen配置 Spring Boot提供了一系列的starter pom用来简化我们的Maven依赖,下边是创建一个web项目中自动包含的依赖,使用的starter pom以来为:spring-boot-starter-web spring-boot-starter-web:支持全栈web开发,里面包括了Tomcat和Spring-webmvc。 spring-boot-starter-mail:提供对javax.mail的支持. spring-boot-starter-ws: 提供对Spring Web Services的支持 spring-boot-starter-test:提供对常用测试框架的支持,包括JUnit,Hamcrest以及Mockito等。 spring-boot-starter-actuator:支持产品环境下的一些功能,比如指标度量及监控等。 spring-boot-starter-jetty:支持jetty容器。 spring-boot-starter-log4j:引入默认的log框架(logback) Spring Boot官网还提供了很多的starter pom,请参考: springboot官网 (4)自动配置Spring Spring Boot会根据我们项目中类路径的jar包/类,为jar包的类进行自动配置Bean,这样一来就大大的简化了我们的配置。当然,这只是Spring考虑到的大多数的使用场景,在一些特殊情况,我们还需要自定义自动配置; (5)应用监控 Spring Boot提供了基于http、ssh、telnet对运行时的项目进行监控;
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/106670.html原文链接:https://javaforall.cn