当前位置:网站首页>YML configuration, binding and injection, verification, unit of bean
YML configuration, binding and injection, verification, unit of bean
2022-07-05 23:09:00 【ZJH'blog】
Configured rules
- Try to be all lowercase
- Support for loose binding ( Lower case numbers underline )
- @Value Loose binding is not supported
Three ways to inject
The same Bean There can only be one injection , Multiple injections will report errors (Bean Is a singleton )
@Component Inject
1,config class
@Component// Loading configuration properties must be subject to spring Control and control , Inject first bean
@Data// Loading configuration properties must have set
@ConfigurationProperties(prefix = "aliyossphoto")
public class OSSphotoConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2, Start class
Can directly run.getBean(OSSphotoConfig.class)
@SpringBootApplication
public class BootAjaxtestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(BootAjaxtestApplication.class, args);
OSSphotoConfig bean = run.getBean(OSSphotoConfig.class);
System.out.println(bean);
}
@Bean + @ConfigurationProperties
1,config Class cannot be injected @Component
@Data// Loading configuration properties must have set
public class OSSphotoConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2, The startup class needs @Bean Inject , as for @ConfigurationProperties(prefix = “”)
You can write anywhere , As long as config If there is a binding in the class or startup class
@SpringBootApplication
public class BootAjaxtestApplication {
@Bean
@ConfigurationProperties(prefix = "aliyossphoto")
public OSSphotoConfig getbean(){
OSSphotoConfig osSphotoConfig = new OSSphotoConfig();
return osSphotoConfig;
}
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(BootAjaxtestApplication.class, args);
OSSphotoConfig bean = run.getBean(OSSphotoConfig.class);
System.out.println(bean);
}
@EnableConfigurationProperties({class,class})
- This annotation can clearly see what has been injected Bean, At the same time @Component Conflict , Also with the @Bean Conflict ; however Need to be in config Class
- {} Using reflection , Multiple can be injected at the same time Bean
1,config class
@ConfigurationProperties(prefix = "aliyossphoto")
@Data// Loading configuration properties must have set
public class OSSphotoConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2, Start the class
@EnableConfigurationProperties({OSSphotoConfig.class})
@SpringBootApplication
public class BootAjaxtestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(BootAjaxtestApplication.class, args);
OSSphotoConfig bean = run.getBean(OSSphotoConfig.class);
System.out.println(bean);
}}
Bean The operation of
- run.getBean(xxx.class) The object obtained is due to @Data The existence of can call get set Method
- Get the attribute value in addition to get The method can also be used @Value("${xx.xx}")
- In main class , Test class ,MVC Layers can be directly @Autowired obtain , But in the ordinary class, you need to use the tool class
Tool class implementation ApplicationContextAware Interface
Create a tool class under any package , This tool class can be obtained through reflection bean, No need to pass @Autowired or @Bean It can be used in ordinary classes bean
And this tool class is general
Use it directly SpringContext.getBean(xxx.class) obtain bean that will do
@Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } // Static loading applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } // Get by reflection Bean public static <T> T getBean(Class<T> requiredType){ return getApplicationContext().getBean(requiredType); } // adopt id Name acquisition bean public static <T> T getBean(String name){ return (T) getApplicationContext().getBean(name); } }
@Value
Unit configuration
@XxxxxUnit
Property verification validation+validator
1,maven coordinate , You can't have one without the other
1,1 JSR303 standard
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
1,2 Hibernate validator Property validator
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2, Enable attribute injection verification @[email protected] etc.
@ConfigurationProperties(prefix = "aliyossphoto")
@Data// Loading configuration properties must have set
@Validated
public class OSSphotoConfig {
@Max(value = 200, message = " The maximum value does not exceed 200")
@Min(value = 0 , message = " The minimum value cannot be lower than 0")
private Integer age;
}
There are many verification rules , Just search it when you have specific needs
边栏推荐
- Nacos 的安装与服务的注册
- Boring boring
- 一文搞定JVM常见工具和优化策略
- 3D point cloud slam
- 基于脉冲神经网络的物体检测
- Sum of two numbers, sum of three numbers (sort + double pointer)
- PLC编程基础之数据类型、变量声明、全局变量和I/O映射(CODESYS篇 )
- Leetcode buys and sells stocks
- Global and Chinese markets of tantalum heat exchangers 2022-2028: Research Report on technology, participants, trends, market size and share
- 一文搞定class的微观结构和指令
猜你喜欢
LeetCode102. Sequence traversal of binary tree (output by layer and unified output)
Spectrum analysis of ADC sampling sequence based on stm32
Registration of Electrical Engineering (elementary) examination in 2022 and the latest analysis of Electrical Engineering (elementary)
Three.JS VR看房
Arduino measures AC current
Common JVM tools and optimization strategies
Selenium+pytest automated test framework practice
Debian 10 installation configuration
Fix the memory structure of JVM in one article
One article deals with the microstructure and instructions of class
随机推荐
Yiwen gets rid of the garbage collector
Déterminer si un arbre binaire est un arbre binaire complet
openresty ngx_ Lua regular expression
Data type, variable declaration, global variable and i/o mapping of PLC programming basis (CoDeSys)
Nacos 的安装与服务的注册
regular expression
Basic knowledge of database (interview)
One article deals with the microstructure and instructions of class
Paddy serving v0.9.0 heavy release multi machine multi card distributed reasoning framework
Function default parameters, function placeholder parameters, function overloading and precautions
[speech processing] speech signal denoising and denoising based on Matlab GUI low-pass filter [including Matlab source code 1708]
Use the rewrite rule to rewrite all accesses to the a domain name to the B domain name
3D point cloud slam
Simple and beautiful method of PPT color matching
利用LNMP实现wordpress站点搭建
d3dx9_ What if 29.dll is missing? System missing d3dx9_ Solution of 29.dll file
Un article traite de la microstructure et des instructions de la classe
3D reconstruction of point cloud
Realize reverse proxy client IP transparent transmission
Roman numeral to integer