(2)springboot- @Configuration和@ConfigurationProperties

@Configuration

  • @Configuation等价于<Beans></Beans>

  • @Bean等价于<Bean></Bean>

  • @ComponentScan等价于<context:component-scan base-package=”com.dxz.demo”/>;该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>。

     

两种方法,1.使用包扫描 ,创建bean     2. 使用函数创建bean:

方法一

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //1使用配置注解 ,表示这个类是配置文件
@ComponentScan("com.wisely.highlight_spring4.ch1.di") //2使用扫描注解
public class DiConfig {
}

方法二

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //1表示配置文件 
public class JavaConfig {
  @Bean //2spring调用这个方法直接把FunctionService这个类实例加入到spring容器中
  public FunctionService functionService(){
    return new FunctionService();
  }
}

-------------------------------------------------

//没有加Service注解
public class FunctionService {
  public String sayHello(String word){
  return "Hello " + word +" !";
  }
}

@ConfigurationProperties

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

 配置类

@Configuration
@EnableSwagger2
//显式的指定具体的Properties类,不通过扫描的方式,更清晰;
//另也不需要在@ConfigurationProperties注解的自定义Properties类上加@Component
@EnableConfigurationProperties(value = {
        Person.class
})
public class SpringBootConfiguration {
 
}

属性注入的类 

package com.springboot.bean;
 
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
 
import java.util.Date;
import java.util.List;
import java.util.Map;
 
//后面会在配置类中使用@EnableConfigurationProperties注解,如果是用该注解,则不需要将该属性类上添加@Component注解
//@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
 
    private String lastName;
 
    private int age;
 
    private Boolean boss;
 
    private Date birth;
 
    private Map<String,Object> maps;
 
    private List<Object> lists;
 
    private Dog dog;
 
}

yaml文件:

person:
    lastname: liqingfeng
    age: 23
    boss: false
    birth: 1995/10/04
    maps: {k1: v1,k2: v2}
    lists:
      - list1
      - list2
    dog:
      name: 小狗
      age: 2

也可以properties:

person.last-name=guoanni
person.age=25
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=金毛
person.dog.age=4

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值