使用Java的方式配置Spring
实体类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
//@Component表示这个类被Spring接管了,注册到容器中
public class Dog {
@Value("小黑")
//属性注入值
private String name;
@Override
public String toString() {
return "Dog{" +
"name='" + name + ''' +
'}';
}
}
配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.import;
@Configuration
//@Configuration声明这是一个配置类,相当于bean.xml
public class Myconfig {
@Bean
//@Bean注册一个bean,相当于一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,相当于bean标签中的class属性
public Dog dog(){
return new Dog();
}
}
测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(Myconfig.class);
Dog user = context.getBean("dog", Dog.class);
System.out.println(user.toString());
}
}