一. 创建配置类来代替xml配置文件
添加@Configuration让类成为配置类;
添加@ComponentScan(basePackages = {" "}),在basePackages添加要扫描的包
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"pojo","service","dao"})
public class SpringConfig {
}
二. 加载配置类
将原本加载配置文件换成加载配置类
package pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value(value = "Tom")
private String userName;
@Value(value = "123456")
private String password;
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
import config.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;
public class testSpring {
@Test
public void test() {
//加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
User user = context.getBean("user", User.class);
System.out.println(user.toString()); //User{userName='Tom', password='123456'}
}
}
本文介绍了如何在Spring Boot项目中使用Java配置类替换XML配置,包括@Configuration注解和@ComponentScan的使用。通过实例演示了如何加载配置类并获取Bean。

被折叠的 条评论
为什么被折叠?



