9.使用Java的方式配置Spring
我们现在要完全不适应Spring的xml配置了,全权交给Java来做
JavaConfig是Spring的一个子项目,在Spring4之后成为了一个核心功能
实体类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.lwj.pojo;
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;
@Component public class User { @Value("张三") private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
|
配置类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.lwj.config;
import com.lwj.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.lwj") public class MyConfig {
@Bean public User getUser(){ return new User(); } }
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import com.lwj.config.MyConfig; import com.lwj.pojo.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
@org.junit.Test public void test1(){ ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User user = (User) context.getBean("getUser"); System.out.println(user.getName()); } }
|
这种Java配置方式,在Spring Boot中随处可见!