1. 程式人生 > 其它 >使用JavaConfig實現配置

使用JavaConfig實現配置

//@Configuration代表這是一個配置類,就和之前的xml配置檔案一樣,這個也會Spring容器託管,註冊到容器中,因為@Configuration 本來就是一個@Component


@Configuration
@Import(xxx.class)//可以將多個配置引入
@ComponentScan("xxxx.xxxx") //可以通過@ComponentScan("xxxx.xxxx")指定到具體的類
public class Config {
    //註冊一個bean,相當於在xml配置檔案中寫的Bean標籤
    //getUser這個方法名,相當於bean標籤中的id屬性
    //這個方法的返回值,相當於bean標籤中的class屬性
    @Bean
    public User getUser(){
        return new User();//返回要注入到的bean的物件
    }
}

public class MyTest {
    public static void main(String[] args) {
        //使用配置類配置檔案,通過AnnotationConfig 上下文獲取容器,通過配置類的class物件載入
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

        User getUser = (User) context.getBean("getUser");
    }
}