Spring可以不用xml,完全用注解代替,不用单独写xml,用一个配置类装载bean就行了
pojo
package com.cbbpp.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
@Value("小强")
public void setName(String name) {
this.name = name;
}
}
配置类
package com.cbbpp.config;
import com.cbbpp.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,相当于之前的applicationContext.xml配置文件
@Configuration
@ComponentScan("com.cbbpp")
public class MyConfig {
//注册一个Bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象
}
}
测试类
import com.cbbpp.config.MyConfig;
import com.cbbpp.pojo.User;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void test(){
//如果完全使用了配置类方式去做,我们只能通过AnnotationConfig上下文获取容器,通过配置类的class对象加载
AnnotationConfigApplicationContext anno = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = anno.getBean("getUser",User.class);
System.out.println(getUser);
}
}