9. 使用JAVA方法配置Spring
现在要完全不使用Spring的xml配置,全程交给Java
JavaConfig是Spring的一个子项目,在Spring4之后成为了核心功能
官方文档:1.12.1
配置文件:
import com.Yurrize.pojo.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;
@Configuration
@ComponentScan("com.Yurrize.pojo")
@Import(YurrizeConfig2.class)
public class YurrizeConfig {
@Bean
public User getUser(){
return new User();
}
}
实体类:
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("Yurrize")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
测试类:
import com.Yurrize.config.YurrizeConfig;
import com.Yurrize.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(YurrizeConfig.class);
User getUser = context.getBean("getUser", User.class);
System.out.println(getUser);
}
}
? 这种纯JAVA的配置方式,在SpringBoot中随处可见
|