为什么我的@Autowired字段在这里为空?

时间:2015-07-23 08:07:43

标签: spring hibernate

this question的副本。所以请不要关闭它,因为" "的副本。原因..

我正在尝试使用this tutorial在我的服务类中自动装配私有字段。我的问题是restaurantOwnerRepository仍然是null,并且没有初始化。

servlet的context.xml中

<context:component-scan base-package="com.mahlzeit.web.server" />

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>

<tx:annotation-driven />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="restaurantOwnerRepository" class="com.mahlzeit.web.server.dao.RestaurantOwnerRepository">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
</bean>  

服务代码:

@Component
public class RestaurantInformationServiceImpl  extends XsrfProtectedServiceServlet implements RestaurantInformationService {
    private static final long serialVersionUID = -4088840947018614411L;

    @Autowired
    private RestaurantOwnerRepository restaurantOwnerRepository;

    private final static Logger logger = Logger.getLogger(RestaurantInformationServiceImpl.class);

    @Override
    public List<RestaurantDTO> getAvailableRestaurants() {

        // restaurantOwnerRepository is 'null'
        List<Restaurant> availableRestaurants = restaurantOwnerRepository.getAvailableRestaurants(getSessionId());

        return null;
    }

    private String getSessionId() {
        HttpServletRequest httpRequest = getThreadLocalRequest();
        return httpRequest.getSession().getId();
    }
}

RestaurantOwnerRepository.java

public class RestaurantOwnerRepository implements RestauranOwnerDAO {

    private SessionFactory sessionFactory;

    public RestaurantOwnerRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // ..
}

这可能是什么原因?

1 个答案:

答案 0 :(得分:0)

这是一个示例控制器,您应该在context.xml中定义bean,或者如果将它放在这个包中:com.mahlzeit.web.server它将由spring自动管理,因为我看到你已经放置了上下文:component-scan

@Controller
public class RestaurantInformationServiceImpl  {

    @Autowired
    private RestaurantOwnerRepository restaurantOwnerRepository;

    @RequestMapping(value="/")
    public @ResponseBody ModelAndView getRestaurants( 
    HttpServletRequest request, 
    HttpServletResponse response) { 
            ModelAndView model = new ModelAndView("yourPage");
            List<?> rests = restaurantOwnerRepository.getAvailableRestaurants(httpRequest.getSession().getId());
            model.addObject("restList", rests );
            return model;
        }

}