1、@Configuration
Full模式:配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
Lite模式:配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- #############################Configuration使用示例######################################################
- /**
- * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
- * 2、配置类本身也是组件
- * 3、proxyBeanMethods:代理bean的方法
- * Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
- * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
- * 组件依赖必须使用Full模式默认。其他默认是否Lite模式
- *
- *
- *
- */
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- public class MyConfig {
-
- /**
- * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
- * @return
- */
- @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
- public User user01(){
- User zhangsan = new User("zhangsan", 18);
- //user组件依赖了Pet组件
- zhangsan.setPet(tomcatPet());
- return zhangsan;
- }
-
- @Bean("tom")
- public Pet tomcatPet(){
- return new Pet("tomcat");
- }
- }
-
-
- ################################@Configuration测试代码如下########################################
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan("com.atguigu.boot")
- public class MainApplication {
-
- public static void main(String[] args) {
- //1、返回我们IOC容器
- ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
-
- //2、查看容器里面的组件
- String[] names = run.getBeanDefinitionNames();
- for (String name : names) {
- System.out.println(name);
- }
-
- //3、从容器中获取组件
-
- Pet tom01 = run.getBean("tom", Pet.class);
-
- Pet tom02 = run.getBean("tom", Pet.class);
-
- System.out.println("组件:"+(tom01 == tom02));
-
-
- //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
- MyConfig bean = run.getBean(MyConfig.class);
- System.out.println(bean);
-
- //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
- //保持组件单实例
- User user = bean.user01();
- User user1 = bean.user01();
- System.out.println(user == user1);
-
-
- User user01 = run.getBean("user01", User.class);
- Pet tom = run.getBean("tom", Pet.class);
-
- System.out.println("用户的宠物:"+(user01.getPet() == tom));
-
-
-
- }
- }
spring 中的老注解
- * 4、@Import({User.class, DBHelper.class})
- * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
- *
- *
- *
- */
-
- @Import({User.class, DBHelper.class})
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- public class MyConfig {
- }
条件装配:满足Conditional指定的条件,则进行组件注入
- =====================测试条件装配==========================
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- //@ConditionalOnBean(name = "tom")
- @ConditionalOnMissingBean(name = "tom")
- public class MyConfig {
-
-
- /**
- * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
- * @return
- */
-
- @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
- public User user01(){
- User zhangsan = new User("zhangsan", 18);
- //user组件依赖了Pet组件
- zhangsan.setPet(tomcatPet());
- return zhangsan;
- }
-
- @Bean("tom22")
- public Pet tomcatPet(){
- return new Pet("tomcat");
- }
- }
-
- public static void main(String[] args) {
- //1、返回我们IOC容器
- ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
-
- //2、查看容器里面的组件
- String[] names = run.getBeanDefinitionNames();
- for (String name : names) {
- System.out.println(name);
- }
-
- boolean tom = run.containsBean("tom");
- System.out.println("容器中Tom组件:"+tom);
-
- boolean user01 = run.containsBean("user01");
- System.out.println("容器中user01组件:"+user01);
-
- boolean tom22 = run.containsBean("tom22");
- System.out.println("容器中tom22组件:"+tom22);
-
-
- }
原生配置文件引入,导入Spring的配置文件(xml)
- ======================beans.xml=========================
- <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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
-
- <bean id="haha" class="com.atguigu.boot.bean.User">
- <property name="name" value="zhangsan">property>
- <property name="age" value="18">property>
- bean>
-
- <bean id="hehe" class="com.atguigu.boot.bean.Pet">
- <property name="name" value="tomcat">property>
- bean>
- beans>
- @ImportResource("classpath:beans.xml")
- public class MyConfig {}
-
- ======================测试=================
- boolean haha = run.containsBean("haha");
- boolean hehe = run.containsBean("hehe");
- System.out.println("haha:"+haha);//true
- System.out.println("hehe:"+hehe);//true
在Bean上标注
- /**
- * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
- */
- @Component
- @ConfigurationProperties(prefix = "mycar")
- public class Car {
-
- private String brand;
- private Integer price;
-
- public String getBrand() {
- return brand;
- }
-
- public void setBrand(String brand) {
- this.brand = brand;
- }
-
- public Integer getPrice() {
- return price;
- }
-
- public void setPrice(Integer price) {
- this.price = price;
- }
-
- @Override
- public String toString() {
- return "Car{" +
- "brand='" + brand + '\'' +
- ", price=" + price +
- '}';
- }
- }
在Bean上标注@ConfigurationProperties,在Bean Configure上标注@EnableConfigurationProperties
- @EnableConfigurationProperties(Car.class)
- //1、开启Car配置绑定功能
- //2、把这个Car这个组件自动注册到容器中
- public class MyConfig {
- }
xxxxxAutoConfiguration ---> 组件 ---> xxxxProperties里面拿值 ----> application.properties
相当于以下3个注解,是一个合成注解
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
- @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
- public @interface SpringBootApplication{}
@Configuration。代表当前是一个配置类
指定扫描哪些,Spring注解;
相当于以下2个注解,是一个合成注解
- @AutoConfigurationPackage
- @Import(AutoConfigurationImportSelector.class)
- public @interface EnableAutoConfiguration {}
7.3.1 @AutoConfigurationPackage
自动配置包?指定了默认的包规则
- @Import(AutoConfigurationPackages.Registrar.class) //给容器中导入一个组件
- public @interface AutoConfigurationPackage {}
-
- //利用Registrar给容器中导入一系列组件
- //将指定的一个包下的所有组件导入进来?MainApplication 所在包下。
7.3.2 @Import(AutoConfigurationImportSelector.class)
- 1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
- 2、调用List
configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类 - 3、利用工厂加载 Map
> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件 - 4、从META-INF/spring.factories位置来加载一个文件。
- 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
- spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
- 虽然我们127个场景的所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
- 按照条件装配规则(@Conditional),最终会按需配置。
- @Bean
- @ConditionalOnBean(MultipartResolver.class) //容器中有这个类型组件
- @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
- public MultipartResolver multipartResolver(MultipartResolver resolver) {
- //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
- //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
- // Detect if the user has created a MultipartResolver but named it incorrectly
- return resolver;
- }
- 给容器中加入了文件上传解析器;
- @Bean
- @ConditionalOnMissingBean
- public CharacterEncodingFilter characterEncodingFilter() {
- //SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先
-
- }
@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody
- @RestController
- public class ParameterTestController {
-
-
- // car/2/owner/zhangsan
- @GetMapping("/car/{id}/owner/{username}")
- public Map
getCar(@PathVariable("id") Integer id, - @PathVariable("username") String name,
- @PathVariable Map
pv, - @RequestHeader("User-Agent") String userAgent,
- @RequestHeader Map
header, - @RequestParam("age") Integer age,
- @RequestParam("inters") List
inters, - @RequestParam Map
params, - @CookieValue("_ga") String _ga,
- @CookieValue("_ga") Cookie cookie){
-
-
- Map
map = new HashMap<>(); -
- // map.put("id",id);
- // map.put("name",name);
- // map.put("pv",pv);
- // map.put("userAgent",userAgent);
- // map.put("headers",header);
- map.put("age",age);
- map.put("inters",inters);
- map.put("params",params);
- map.put("_ga",_ga);
- System.out.println(cookie.getName()+"===>"+cookie.getValue());
- return map;
- }
-
-
- @PostMapping("/save")
- public Map postMethod(@RequestBody String content){
- Map
map = new HashMap<>(); - map.put("content",content);
- return map;
- }
-
-
- //1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
- //2、SpringBoot默认是禁用了矩阵变量的功能
- // 手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
- // removeSemicolonContent(移除分号内容)支持矩阵变量的
- //3、矩阵变量必须有url路径变量才能被解析
- @GetMapping("/cars/{path}")
- public Map carsSell(@MatrixVariable("low") Integer low,
- @MatrixVariable("brand") List
brand, - @PathVariable("path") String path){
- Map
map = new HashMap<>(); -
- map.put("low",low);
- map.put("brand",brand);
- map.put("path",path);
- return map;
- }
-
- // /boss/1;age=20/2;age=10
-
- @GetMapping("/boss/{bossId}/{empId}")
- public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
- @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
- Map
map = new HashMap<>(); -
- map.put("bossAge",bossAge);
- map.put("empAge",empAge);
- return map;
-
- }
-
- }
WebRequest、ServletRequest、MultipartRequest、 HttpSession、javax.servlet.http.PushBuilder、Principal、InputStream、Reader、HttpMethod、Locale、TimeZone、ZoneId
- @Override
- public boolean supportsParameter(MethodParameter parameter) {
- Class> paramType = parameter.getParameterType();
- return (WebRequest.class.isAssignableFrom(paramType) ||
- ServletRequest.class.isAssignableFrom(paramType) ||
- MultipartRequest.class.isAssignableFrom(paramType) ||
- HttpSession.class.isAssignableFrom(paramType) ||
- (pushBuilder != null && pushBuilder.isAssignableFrom(paramType)) ||
- Principal.class.isAssignableFrom(paramType) ||
- InputStream.class.isAssignableFrom(paramType) ||
- Reader.class.isAssignableFrom(paramType) ||
- HttpMethod.class == paramType ||
- Locale.class == paramType ||
- TimeZone.class == paramType ||
- ZoneId.class == paramType);
- }
Map、Model(map、model里面的数据会被放在request的请求域 request.setAttribute)、Errors/BindingResult、RedirectAttributes( 重定向携带数据)、ServletResponse(response)、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder
Map
Map、Model类型的参数,会返回 mavContainer.getModel();---> BindingAwareModelMap 是Model 也是Map,mavContainer.getModel(); 获取到值的
可以自动类型转换与格式化,可以级联封装。
- /**
- * 姓名: <input name="userName"/>
- * 年龄: <input name="age"/>
- * 生日: <input name="birth"/>
- * 宠物姓名:<input name="pet.name"/>
- * 宠物年龄:<input name="pet.age"/>
- */
- @Data
- public class Person {
-
- private String userName;
- private Integer age;
- private Date birth;
- private Pet pet;
-
- }
-
- @Data
- public class Pet {
-
- private String name;
- private String age;
-
- }
-
- result
@NoArgsConstructor
生成无参构造器
@AllArgsConstructor
生成有参构造器
@Data
自动生成 get set 方法
@ToString
重写toString方法
@EqualsAndHashCode
重写hash方法
@Slf4j
日志
web原生组件注入:
@ServletComponentScan(basePackages = "com.atguigu.admin") :指定原生Servlet组件都放在那里
@WebServlet(urlPatterns = "/my"):效果:直接响应,没有经过Spring的拦截器?
@WebFilter(urlPatterns={"/css/*","/images/*"})
@WebListener
15. Mybatis
@Mapper
@MapperScan
@TableName
MybatisPlus 中将表和Mapper映射