使用Java的方式配置Spring
重要!!!重要!!!重要!!!
代码演示
实体类
package com.tian.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
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 + '\'' +
'}';
}
}
配置文件
package com.tian.config;
import com.tian.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.tian.pojo")
@Import(TianConfig2.class)
public class TianConfig {
@Bean
public User getUser(){
return new User();
}
}
测试类
import com.tian.config.TianConfig;
import com.tian.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TianConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}
这种纯java的配置方式,在SpringBoot随处可见!
多多练习,尽量把之前的beans.xml文件都改成纯java配置
|