这种纯Java的配置文件,在SpringBoot中随处可见
代码及其注解的作用:
1、定义实体类:
@Component
public class User {
@Value("1")
private int id;
@Override
public String toString() {
return "User{" +
"id=" + id +
'}';
}
}
2、编写config.java文件
关于配置Bean的方式,大家尤其关注代码中的注释内容,详细的介绍都在注释中
import com.guohui.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:声明这个类是一个配置类,相当于之前的applicationContext.xml
@Configuration
//@ComponentScan:扫描某个包下的注解,视为有效状态
@ComponentScan("com.guohui.pojo")
//@Import:相当于applicationContext.xml中的导入其他配置文件的标签,
@Import(MyConfig01.class)
public class MyConfig {
/*这里的@Bean相当于applicationContext.xml中的<bean/>标签
* 方法名getUser相当于bean标签中的id
* 这个方法的返回值return new User(),就相当于bean标签中的class*/
@Bean
public User getUser(){
return new User();
}
}
3、测试:
public class MyTest {
@Test
public void MyTest(){
//通过JavaConfig的方式配置Bean,则需要用到AnnotationConfigApplicationContext这个上下文对象获取容器
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//这里的getUser就是Config.java中的方法名
User user = context.getBean("getUser", User.class);
System.out.println(user.toString());
}
}
4、控制台:
至此,你就掌握了关于Java中如何通过配置类来进行常见类的注入,通过配置类,你就可以将已有些工作中使用到的某些类注入到Spring容器中,直接在需要使用的业务类中通过@Autowired注解将这个类注入进来就能使用类中的方法了!
预祝各位早日成为Java全栈工程师,后续还会持续更新关于Spring的相关技术栈介绍,敬请期待!