使用JavaConfig实现配置
大约 2 分钟Spring全家桶Spring入门
- @Component 放在类上,说明这个类被Spring管理了,就是bean
- @Value 可以放在属性上,也可以放在set方法上
- @Repository dao层
- @Service service层
- @Controller controller层
- @Scope 作用域
- @Configuration 这个也会被Spring容器托管,注册到容器中。因为它本来就是一个Component。代表这是一个配置类,就和之前看到的beans.xml一样
- @ComponentScan 自动扫描指定包下的注解
- @Import 导入配置类
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!
实体类User.java
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author Administrator
* Component 说明这个类被Spring接管了,注册到了容器中
*/
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("张三三")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
KuangConfig.java
package com.kuang.config;
import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Administrator
* Configuration 这个也会被Spring容器托管,注册到容器中。因为它本来就是一个Component
* Configuration代表这是一个配置类,就和之前看到的beans.xml一样
*/
@Configuration
@ComponentScan("com.kuang.pojo")
@Import(KuangConfig2.class)
public class KuangConfig {
/**
* 注册一个bean,就相当于之前写的一个bean标签
* 这个方法的名字,就相当于bean标签中的id属性
* 这个方法的返回值,就相当于bean标签中的class属性
*/
@Bean
public User getUser(){
/**
* 返回要注入到bean的对象
*/
return new User();
}
}
KuangConfig2.java
package com.kuang.config;
import org.springframework.context.annotation.Configuration;
/**
* @author Administrator
*/
@Configuration
public class KuangConfig2 {
}
测试类MyTest.java

import com.kuang.config.KuangConfig;
import com.kuang.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
/**
* 如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文获取容器
* 通过配置类的class对象加载
*/
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
User user = context.getBean("getUser", User.class);
System.out.println(user.getName());
}
}
结果
张三三
纯Java的配置方式,在SpringBoot中随处可见!