SpringBoot学习笔记(三)

注解:

@Configuration----1.定义配置类,告诉Boot这是一个配置类
                  2.有boolean proxyBeanMethods() default true;-------代理bean的方法
   * Full(proxyBeanMethods=true):有依赖关系,方法会调用得到之前单实例组件,用full模式
   * lite(proxyBeanMethods=false):配置类组件没有依赖关系的话用这个可以加速进程 
   * 组件依赖
@Bean ----给容器中添加组件,以方法名作为组件的id,返回类型就是组件类型,注意这里默认是单实例
 注意: 配置类本身也是组件
import org.springframework.context.annotation.Configuration;
/**
 * @Configuration//告诉Boot这是一个配置类
 * @Bean //给容器中添加组件,以方法名作为组件的id,返回类型就是组件类型,注意这里默认是单实例
 * 配置类本身也是组件
 * @Configuration中有boolean proxyBeanMethods() default true;-------代理bean的方法
 * Full(proxyBeanMethods=true):有依赖关系,方法会调用得到之前单实例组件,用full模式
 * lite(proxyBeanMethods=false):配置类组件没有依赖关系的话用这个可以加速进程
 * 组件依赖
 */
@Configuration(proxyBeanMethods=true)//告诉Boot这是一个配置类
public class MyConfig {
    @Bean
    public User user01(){
        User zhangsan=new User("张三",18);
        zhangsan.setPet(tomcatPet());//这里是user组件依赖了pet组件
          return zhangsan;
    }
    @Bean("tom")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

@Import-----导入组件:放在配置类上

@Conditional-----导入组件:放在配置类上(ConditionalOnBean,ConditionalOnMissingBean)

@ImportResource----导入配置资源(例如导入XML文件,放在配置类上方指定资源路径@ImportResource("classpath:beans.xml")

@ConfigurationProperties----1.@Component+@ConfigurationProperties(prefix="")

                                             2.@Component+配置类上@EnableConfigurationProperties(.....class)

package com.cxy.boot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
//类里面的属性和配置文件里面前缀为mycar的绑定后,再自动注入
@Component//只有在容器中的组件才有springboot的强大
@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 +
                '}';}
}
法二

@Import({User.class, CharTypes.class})
@Configuration(proxyBeanMethods=true)//告诉Boot这是一个配置类
@EnableConfigurationProperties(Car.class)//开启Car配置绑定功能,并把其自动注册到容器中
public class MyConfig {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值