有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

属性“dataSource”处的java Jdbc Spring是必需的或空指针

当我在mapRow完成后运行compile()时。这个错误给了我Property 'dataSource' is required。我的xml上有这个

<bean id="ProcedureRepository" class="mypackage.ProcedureRepository">
    <property name="dataSource" ref="dataSource"/>
</bean>

我的java ProcedureRepository

private DataSource dataSource;

@Resource
@Qualifier("dataSource")
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

public String searchCode(String code){
    new SeachCode(dataSource).execute(code);
    return code;
}

我的密码

public class SearchCode extends StoredProcedure{
public SearchCode(DataSource dataSource) {
    super(dataSource, "MYPROC");
...

compile();

当我称之为:

ProcedureRepository procedureRepository = new ProcedureRepository();
procedureRepository.searchCode(parameters.code);

我不知道我遗漏了什么,我试图在我的xml中添加新bean,但没有成功,在SearchCode添加新的setDataSource


共 (1) 个答案

  1. # 1 楼答案

    当您使用new创建存储库时,只会得到一个不由Spring容器管理的对象。如果你想得到一个Springbean,它拥有Spring注入的所有依赖项,你可以从Spring应用程序上下文中得到它。 例如:

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("path to spring app context xml file)");    
    ProcedureRepository repo= (ProcedureRepository) applicationContext.getBean("ProcedureRepository");
    repo.searchCode(parameters.code)
    

    Here您可以阅读更多关于从Spring应用程序上下文获取bean的信息