- Spring boot通常有⼀个名为 xxxApplication的类,⼊⼝类中有⼀个main⽅法, 在main⽅法中使⽤ **SpringApplication.run(xxxApplication.class,args)**启 动springboot应⽤的项⽬。
- @RestController: 就是 @Controller+@ResponseBody 组合,⽀持RESTful访问⽅ 式,返回结果都是json字符串。
- @SpringBootApplication 注解等价于:
- @SpringBootConfiguration 标识注解,标识这是⼀个springboot的配置类
- @EnableAutoConfiguration ⾃动与项⽬中集成的第三⽅技术进⾏集成
- @ComponentScan 扫描⼊⼝类所在⼦包以及⼦包后代包中注解
配置文件的拆分
拆分如下:
application.yml
server:
port: 8080
application-pord.yml
server:
context-path: /abcd
application-dev.yml
server:
context-path: /springboot
- 使⽤ @Repository @Service @Controller 以及 @Component管理不同简单对象 如: ⽐如要通过⼯⼚创建⾃定义User对象:
@Component
@Data
public class User {
private String id;
private String name;
......
}
@Controller
@RequestMapping("hello")
public class HelloController {
@Autowired
private User user;
......
}
@Configuration(推荐)|@Component(不推荐)
public class Beans {
@Bean
public Calendar getCalendar(){
return Calendar.getInstance();
}
}
- @Configuration 配置注解主要⽤来⽣产多个组件交给⼯⼚管理 (注册形式)
- @Component ⽤来管理单个组件(包扫描形式)
@Controller
@RequestMapping("hello")
public class HelloController {
@Value("${name}")
private String name;
}
- @ConfigurationProperties(prefix="前缀")
@Component
@Data
@ConfigurationProperties(prefix = "user")
public class User {
private String id;
private String name;
private Integer age;
private String bir;
}
user:
id: 22
name: username
age: 22
bir: 2022/12/12
aop
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starteraop</artifactId>
</dependency>
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.sovue.service.*.*
(..))")
public void before(JoinPoint joinPoint){
System.out.println("前置通知");
joinPoint.getTarget();
joinPoint.getSignature();
joinPoint.getArgs();
}
}
@Aspect
@Component
public class MyAspect {
@After("execution(* com.sovue.service.*.*
(..))")
public void before(JoinPoint joinPoint){
System.out.println("后置通知");
joinPoint.getTarget();
joinPoint.getSignature();
joinPoint.getArgs();
}
}
@Aspect
@Component
public class MyAspect {
@Around("execution(* com.sovue.service.*.*
(..))")
public Object before(ProceedingJoinPoint
proceedingJoinPoint) throws Throwable {
System.out.println("进⼊环绕通知");
proceedingJoinPoint.getTarget();
proceedingJoinPoint.getSignature();
名
proceedingJoinPoint.getArgs();
Object proceed =
proceedingJoinPoint.proceed();
System.out.println("⽬标⽅法执⾏之后回到环绕通
知");
return proceed;
}
}
boot 下载
@RequestMapping("/download")
public void download(String fileName,
HttpServletRequest request, HttpServletResponse
response) throws Exception {
String realPath =
request.getRealPath("/upload");
FileInputStream is = new
FileInputStream(new File(realPath, fileName));
ServletOutputStream os =
response.getOutputStream();
response.setHeader("contentdisposition","attachment;fileName="+
URLEncoder.encode(fileName,"UTF-8"));
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}