@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