【发布时间】:2015-01-01 04:35:15
【问题描述】:
在搜索了一天之后,尝试了所有配置(应用程序上下文)和注释(自动装配、注入、组件等),我似乎无法让我的 pojo 类成功地注入一个工作存储库——该值始终为空。 我开始怀疑除了控制器之外的任何东西注入是否与 spring data rest 的架构相反。
这是我的应用程序上下文(取自 spring 文档):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.test.springservice"/>
</beans>
我的主要类在:
package com.test.springservice;
import ...
@Configuration
@ComponentScan
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@ImportResource("classpath:WEB-INF/applicationContext.xml")
@EnableAutoConfiguration
@PropertySource("application.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我的工作存储库和模型:
package com.test.springservice.greek;
import ...
@RepositoryRestResource
public interface GreekLetterRepository extends CrudRepository<GreekLetter, Integer> {
@Query("SELECT l FROM GreekLetter l WHERE l.translit Like :translit% ORDER BY length(l.translit) Desc")
public List<GreekLetter> findByTranslitStartsWith(@Param("translit") String translit);
}
package com.test.springservice.greek.model;
import ....
@Entity
@Table(name="letters", catalog="greek")
public class GreekLetter extends Letter {
public GreekLetter() {}
public GreekLetter(String name, String translit, String present, String types) { super(name,translit,present,types); }
}
最后,我无法将存储库注入的类:
package com.test.springservice.greek.model;
import ...
public class GreekString extends Letters {
@Autowired
public GreekLetterRepository repository; // this is null (class not managed by container)
public GreekString(String str) {
super();
setTranslit(str);
if (this.getTranslit().equals(this.getPresent())) { setPresent(str); }
}
public void setTranslit(String str) { // litterates from str as translit
List<Letter> lets = new ArrayList<Letter>();
for (int i = 0; i < str.length(); i++) {
String partialWord = str.substring(i);
String partialWord0 = partialWord.substring(0,1);
List<GreekLetter> potentialMatches = repository.findByTranslitStartsWith(partialWord0);
....
}
....
}
....
}
有没有人看到这种方法的基本缺陷?
提前致谢。
【问题讨论】:
标签: spring dependency-injection spring-boot spring-data-rest