使用java的方式配置Spring
稳现在完全不使用xml配置,java来做
javaConflg是spring的一个子项目,在Spring4后,它成为了一个核心功能。
import com.javapp.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
//把这个类加到容器中,代表这是一个配置类,等价XML文件
@Configuration
@ComponentScan("com.javapp")//导入包
@Import(CSM20.class)//导入类
public class CSm {
//注册一个id="getUser"的Bean
@Bean
public User getUser(){
return new User();
}
}
package com.javapp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//把这个类加到容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
//注入值
@Value("陈声铭")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
import Tesx.CSm;
import com.javapp.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Mytest {
public static void main(String[] arsg){
//如果完全使用了配置类,就只能由AnnotationConfigApplicationContext来获取容器,通过配置类的class对象加载!
ApplicationContext context= new AnnotationConfigApplicationContext(CSm.class);
User user=context.getBean("getUser",User.class);
System.out.println(user.getName());
}
}
纯java的配置方式在Spring Boot中随处可见!