Java中通过类反射创建的对象其中注入的bean对象为null的解决办法 给出具体的代码
时间: 2024-03-22 13:38:48 浏览: 47
用反射实现向不同简单JavaBean填充值的实现代码
3星 · 编辑精心推荐
好的,下面是一些可能的解决办法的代码实现:
1. 手动实例化并加入到Spring容器中
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BeanA beanA = new BeanA();
context.getBeanFactory().registerSingleton("beanA", beanA);
```
2. 修改注解
```java
@Component("beanA")
public class BeanA {
@Autowired(required = true)
private BeanB beanB;
//...
}
@Component("beanB")
public class BeanB {
//...
}
```
3. 修改作用域
```java
@Component("beanA")
@Scope("prototype")
public class BeanA {
@Autowired(required = true)
private BeanB beanB;
//...
}
@Component("beanB")
public class BeanB {
//...
}
```
4. 修改依赖
```java
@Component("beanA")
public class BeanA {
@Autowired(required = true)
private BeanB beanB;
//...
}
@Component("beanB")
public class BeanB {
//...
}
@Component("beanC")
public class BeanC {
@Autowired(required = true)
private BeanB beanB;
//...
}
```
5. 修改属性
```java
@Component("beanA")
public class BeanA {
@Autowired(required = true)
private BeanB beanB;
//...
}
@Component("beanB")
public class BeanB {
private String name;
//...
}
```
阅读全文