首先添加依赖
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>RELEASE</version>
</dependency>
需修改的bean
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "org")
public class TaOrgProperties{
private String test = "abcd";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
获取bean中的值
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller("/test")
@RequestMapping("/test")
public class TestController{
@Autowired
private TaOrgProperties taOrgProperties;
@GetMapping("getProperties")
public void getO(){
System.out.println("====="+taOrgProperties.getTest());
}
}
修改bean中的值
/**
* 扫描注解并修改bean的值
*/
@GetMapping("setProperties")
public void setProperties() {
Reflections reflections = new Reflections("com.project.controller"); // 需要扫描的包
//获取带Component注解的类
Set<Class<?>> classList = reflections.getTypesAnnotatedWith(Component.class); // 需要扫描的注解
for (Class classes : classList) {
Class<?> targetClass = classes;
Field[] fields = targetClass.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals("test")) { // 扫描到的字段名称如果是test,则修改bean中test的值
// 当前字段是需要设置值的字段
field.setAccessible(true);
try {
Object o = ApplicationUtil.getBeanByClassName(targetClass);
field.set(o, "222");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
工具类:applicationContext中获取bean
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationUtil.applicationContext = applicationContext;
}
public static Object getBean(String name){
return applicationContext.getBean(name);
}
public static Object getBeanByClassName(Class className){
return applicationContext.getBean(className);
}
}
再次调用getProperties这个接口获取test的值就为222,不再是abcd