一. 创建配置类来代替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'}
}
}