我们可以将没有默认构造函数的服务 bean 注入(inject)到 Controller 中吗?
我有以下 Controller
@Controller
public class ArticleController {
@Autowired
private WithConstructorService withConstructorService;
...
}
我的服务是:
@Service
public class WithConstructorServiceImpl implements WithConstructorService {
String name;
String address;
public WithConstructorServiceImpl(String name, String address) {
super();
this.name = name;
this.address = address;
}
}
我遇到了异常
SEVERE: Servlet /springheat threw load() exception
java.lang.NoSuchMethodException: WithConstructorServiceImpl.<init>()
更新:
我在这里猜测,但我们可以做一些 AOP 魔术并仍然使用带注释的构造函数 arg 服务方法吗?
最佳答案
如果您使用的是 spring 3,则可以使用 @Value
注释来连接名称和地址字段,然后不需要通过构造函数设置它们。或者,不要使用 @Service
注释,而是使用适当的 <constructor-arg>
在 xml 中声明您的 bean标签。
无论哪种方式,spring 容器都需要知道从哪里获取名称和地址的值,否则它无法构建您的 WithConstructorServiceImpl。
关于java - 在 Controller 中注入(inject)没有默认构造函数的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651273/