@Autowired 报错java.lang.NullPointerException

package com.example.aspectjdemo;

import org.springframework.stereotype.Repository;

@Repository
public interface HelloService {

 void sayHello(String name);

}

package com.example.aspectjdemo;

import org.springframework.stereotype.Service;

@Service
public class HelloServiceImpl implements HelloService{

@Override
public void sayHello(String name) {
    if (null == name || name.trim() == "") {
        throw new RuntimeException("param is null!");
    }
    System.out.println("hello"+name);
}

}

public class TestAspect {

@Autowired
private HelloService helloService;

@Test

public void sayHello(){

    helloService.sayHello("dom");


}

报错代码如下,请问大神如何解决,谢谢!

java.lang.NullPointerException
at com.example.aspectjdemo.TestAspect.sayHello(TestAspect.java:21)

我想你应该注入HelloService的实现类HelloServiceImpl而不是注入HelloService接口

猜一下,你应该是没有启动 spring的环境

注解来看没有问题, TestAspect 类上面缺少注解


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/applicationContext-mvc.xml",
        "classpath:config/applicationContext.xml" })

添加 Spring 配置路径