SpringBoot基础梳理
1.入口类和@SpringBootApplication注解:
SpringBoot通常有一个名为*Application的入口类,入口类里面有main方法,我们可以通过启动main方法启动springboot应用
@SpringBootApplication是SpringBoot的核心注解,他是一个组合注解,源码如下:
1 @Target({ ElementType.TYPE }) 2 @Retention(RetentionPolicy.RUNTIME) 3 @Documented 4 @Inherited 5 @SpringBootConfiguration 6 @EnableAutoConfiguration 7 @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = { TypeExcludeFilter.class }) }) 8 public @interface SpringBootApplication { 9 Class<?>[] exclude() default {}; 10 11 String[] excludeName() default {}; 12 13 @AliasFor(annotation = ComponentScan.class, attribute = "basePackages") 14 String[] scanBasePackages() default {}; 15 16 @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses") 17 Class<?>[] scanBasePackageClasses() default {}; 18 }
如果我们不使用@SpringBootApplication,我们可以直接在入口类上使用
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
其中@EnableAutoConfiguration 是让Springboot根据类路劲中的jar包依赖为当前项目进行自动配置
例如:我们添加了spring-boot-starter-web依赖后,会自动添加Tomcat和SpeingMVC的依赖,那么Spring Boot会对Tomcat和SpringMVC进行自动配置
2.使用xml配置Springboot
我们可以通过@ImportResource来加载xml配置
例如:
@ImportResource("classpath:some-context.xml")
3.基于安全的配置类型
Springboot可以通过@ConfigurationProperties将properties和一个Bean及其属性关联,从而实现安全的配置
例如:
1 @Component 2 @ConfigurationProperties(prefix="author")//通过@ConfigurationProperties加载指定的properties文件内容 3 //通过prefix属性指定properties的配置前缀,通过location指定properties文件的位置,例如: 4 //@ConfigurationProperties(prefix="author",locations="classpath:config/author.properties") 本例不需要配置location 5 public class AuthorSettings { 6 private String name; 7 private Long age; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public Long getAge() { 15 return age; 16 } 17 public void setAge(Long age) { 18 this.age = age; 19 } 20 }
配置文件如下
author.name=xmz
author.age=23
分类:
SpringBoot
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密