Spring学习(7)使用JavaConfig实现配置

tech2022-08-08  120

使用Java的方式配置Spring

现在完全不使用Spring的xml配置,全权交给Java来做!

JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

建一个配置类MyConfig.java

package com.zhao.config; import com.zhao.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; @Configuration @ComponentScan("com.zhao.pojo") //@Import(MyConfig2.class) 导入其他配置文件 public class MyConfig { //注册一个Bean,就相当于之前写的一个bean标签 //这个方法的名字,就相当于bean标签中的id属性 //这个方法的返回值,就相当于bean标签中的class属性 @Bean public User getUser(){ return new User(); //返回要注入到bean中的对象 } }

User.java

package com.zhao.pojo; 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("zhao") public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }

测试类

import com.zhao.config.MyConfig; import com.zhao.pojo.User; import javafx.application.Application; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MyTest { public static void main(String[] args) { //如果完全使用配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象家在! ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User getUser = (User) context.getBean("getUser"); System.out.println(getUser.getName()); } }

这种纯Java的配置方式,在SpringBoot中随处可见

最新回复(0)