2013-08-22 4 views
1

@Service Bean을 QuartzJobBean에 삽입하는 데 문제가 있습니다. this question의 팁을 사용하여 @Repository 빈을 삽입 할 수 있었지만 @Service 빈은 삽입 할 수 없었습니다.QuartzJobBean에 @Service Bean을 삽입하지 못했습니다.

저장소 콩을 MongoDB의 문서에 액세스 할 : 나는 스프링 MVC 컨트롤러에서이면 MyService를 사용할 수 있었다

@Service 
public class MyService { 
    @Autowired 
    private MyRepository myRepository; 

    public void method1() { ... } 
} 

: 비즈니스 로직을 수행 할 수

public interface MyRepository extends MongoRepository<> {} 

서비스 빈을 여기에 내가 가진 무엇 , 그래서 나는 Spring이 그것들을 적절하게 인스턴스화했다는 것을 안다. '내가 할 수있는 schedulerContextAsMap에'는 myService '을 변경하면 내가

'BeanCreationException: Cannot resolve reference to bean 'myService' while setting bean property 'schedulerContextAsMap'있어,

<bean name="myJob" class="org.springframework.scheduling.quartz.JobDetailBean"> 
     <property name="jobClass" value="com.MyJob" /> 
    </bean> 
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
     [jobDetails and triggers omitted] 
     <property name="schedulerContextAsMap"> 
     <map> 
      <entry key="myService"> 
       <ref bean="myService"/> 
      </entry> 

     </map> 
    </property> 
    </bean> 

을이 설정으로 :

다음 나는 QuartzJobBean에서 확장하고 그것으로이면 MyService를 주입하려고 작업을 생성 myRepository '는 효과가있었습니다. 하지만 QuartzJobBean에서 비즈니스 로직을 다시 구현하고 싶지는 않습니다.

myService Bean이 SchedulerFactoryBean에 표시되지 않는 이유는 무엇입니까? BTW, 이미 annotation-config 및 component-scan 태그를 사용할 수 있습니다.

[업데이트 - 컨텍스트 초기화] spring-quartz.xml이 마지막으로 참조되므로 모든 내용이 초기화되어야한다는 것을 알 수 있습니다.

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value> 
     /WEB-INF/spring/root-context.xml, 
     /WEB-INF/spring/spring-security.xml, 
     /WEB-INF/spring/spring-quartz.xml 
     </param-value> 
    </context-param> 
    <listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 
    <servlet> 
    <servlet-name>appServlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> 
     </init-param> 
    <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
    <servlet-name>appServlet</servlet-name> 
    <url-pattern>/</url-pattern> 
    </servlet-mapping> 

루트-context.xml에

<?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:mongo="http://www.springframework.org/schema/data/mongo" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/data/mongo 
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> 

<!-- Root Context: defines shared resources visible to all other web components --> 
<!-- Factory bean that creates the Mongo instance --> 
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean"> 
    <property name="host" value="localhost" /> 
</bean> 

<!-- MongoTemplate for connecting and quering the documents in the database --> 
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 
    <constructor-arg name="mongo" ref="mongo" /> 
    <constructor-arg name="databaseName" value="test" /> 
</bean> 

<!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes --> 
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> 

<mongo:repositories base-package="com.repositories" /> 

</beans> 

서블릿-context.xml에 당신이 당신의 질문에 귀하의 코멘트에 따라 문제를 해결 한 것처럼 보인다

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:beans="http://www.springframework.org/schema/beans" 
xsi:schemaLocation=" 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> 

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

<!-- Enables the Spring MVC @Controller programming model --> 
<annotation-driven conversion-service="conversionService"> 
    <argument-resolvers> 
     <beans:bean class="org.springframework.mvc.data.CustomArgumentResolver"/>   
     <beans:bean class="org.springframework.data.web.PageableArgumentResolver" /> 
    </argument-resolvers> 
</annotation-driven> 

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory --> 
<resources mapping="/resources/**" location="/resources/" /> 

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <beans:property name="prefix" value="/WEB-INF/views/" /> 
    <beans:property name="suffix" value=".jsp" /> 
</beans:bean> 

<!-- Only needed because we install custom converters to support the examples in the org.springframewok.samples.mvc.convert package --> 
<beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    <beans:property name="formatters"> 
     <beans:bean class="org.springframework.mvc.convert.MaskFormatAnnotationFormatterFactory" /> 
    </beans:property> 
</beans:bean> 

<!-- Only needed because we require fileupload in the org.springframework.samples.mvc.fileupload package --> 
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 

<context:annotation-config /> 
<context:component-scan base-package="com" /> 
</beans:beans> 
+1

어떻게 당신은 당신의 애플리케이션 컨텍스트 (들)을 초기화 할 때? 문제를 기반으로, 대부분의 스케줄러는 서비스를 인스턴스화하는 컨텍스트 이전의 컨텍스트에서 인스턴스화됩니다. 질문을 편집하여 컨텍스트를 초기화하는 방법에 대한 세부 정보를 제공하십시오. – kaliatech

+0

당신 말이 맞아요. 내 spring-quartz.xml 파일을 옮겨서 이제는 schedulerFactory가 서비스 참조를 볼 수있다. 감사. – azgolfer

답변

0

. 그러나, just-in-case :

근본적인 문제는 서블릿 컨텍스트에서 구성 요소 검색 만 구성했다는 것입니다. 결과적으로 MyService 주석은 서블릿 컨텍스트가 초기화 될 때만 처리됩니다. Spring-quartz.xml이 ContextLoaderListener에 의해 루트 컨텍스트로 처리 될 때 아직 사용 가능하지 않습니다.

서비스 등에 대한 주석을 사용하는 경우 root-context.xml에서 구성 요소 검색을 활성화하고 서블릿에서 구성 요소 검색에 의해 감지되는 컨트롤러와 같은 항목을 필터링하는 것이 좋습니다 컨텍스트를 사용하여 중복 초기화가 발생하지 않도록하십시오.

서비스 및 웹 코드가 공통 패키지 이름을 공유하는 경우 일반적인 패턴은 필터를 사용하고 컨트롤러를 제외한 모든 항목을 루트 컨텍스트로 검색 한 다음 servet 컨텍스트에서 컨트롤러 및 서블릿 만 검색하여 이 같은 :

루트-context.xml에

<context:component-scan base-package="package"> 
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan> 

서블릿 컨텍스트.xml

물론 다른 많은 옵션이 있습니다. 추가 정보를 원하시면 :

+0

좋은 제안, 팁 주셔서 감사합니다. – azgolfer

관련 문제