Java Autowire注释在控制器中工作,但在其他任何地方都不工作?

Java Autowire注释在控制器中工作,但在其他任何地方都不工作?,java,spring,spring-mvc,autowired,spring-annotations,Java,Spring,Spring Mvc,Autowired,Spring Annotations,我使用的是Spring 4.1.1。 我的spring-dispatcher-servlet.xml中有以下内容 <context:component-scan base-package="com.au.controller,com.au.util" /> <mvc:resources location="/" mapping="/**" /> <mvc:annotation-driven /> <bean id="dataSource" class

我使用的是Spring 4.1.1。 我的spring-dispatcher-servlet.xml中有以下内容

<context:component-scan base-package="com.au.controller,com.au.util" /> 
<mvc:resources location="/" mapping="/**" />
<mvc:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/caballocation" />
    <property name="username" value="root" />
    <property name="password" value="1234" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="AddImplDao" class="com.au.dao.AddressDaoImpl" />
在上面的代码中,obj.select在自动连接时工作

    public class DistanceCalculator {

        @Autowired
        AddressDao obj1;
        public String calculate(String from, String to) throws IOException, JSONException {
        ..
        Map output = obj1.calc(from, to);
        ..
        }
但是com.au.util包中的以下类具有自动连接的对象的值null

    public class DistanceCalculator {

        @Autowired
        AddressDao obj1;
        public String calculate(String from, String to) throws IOException, JSONException {
        ..
        Map output = obj1.calc(from, to);
        ..
        }
执行时Obj1为空。在obj1.calc处获取java.lang.NullPointerException(从、到)

下面是接口及其实现。 AddressDao.java

public interface AddressDao {
    public void select();
    public Map calc(String from,String to);
}
AddressDaoImpl.java

public class AddressDaoImpl implements AddressDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private SimpleJdbcCall simpleJdbcCall;

    @Autowired
    public void setDataSource(DataSource dataSource) {
       this.simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("CheckForValuesInDB");
    }

    @Override
    public void select() {
        // TODO Auto-generated method stub
    }

    @Override
    public Map calc(String from, String to) {
        // TODO Auto-generated method stub}

这背后的原因是什么?

您必须在com.au.controller、com.au.util中添加额外的空间,使其看起来像“com.au.controller、com.au.util”。到目前为止,您的配置只扫描com.au.controller

//编辑
在DistanceCalculator类中应该有@Component annotation

您有任何错误吗?@RossiRobinsion是的,我在DistanceCalculator类中得到了上面提到的nullPointerException,而不是这个。您可以试试这个吗。另外,不要这样做:,而是在AddressDaoImpl类上添加@Service注释。@RossiRobinsion我试过这样做。还是一样error@RossiRobinsion在distanceCalculator.java中,我得到了错误,但在MainController.java中,它是自动连线的