Аннотации @Autowired и @Resource
Всем привет. Подскажите пожалуйста, может быть, кто-нибудь сталкивался.
Изучаю сравнение аннотаций @Autowired и @Resource. Создала класс Dog и Person, у которого есть Dog. Конфигурация через код в классе. Сначала попробовала внедрить зависимость через @Autowired - всё работает. Поменяла на @Resource (несколько вариантов) - выдает NullPointerException. Не могу понять, в чем проблема.
Заранее спасибо.
public interface Pet {
public void voice ();
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component ("dog")
@Scope("singleton")
public class Dog implements Pet {
public Dog () {
System.out.println("Dog start");
}
@PostConstruct
public void init () {
System.out.println("init start - Dog");
}
@PreDestroy
public void destroy () {
System.out.println("destroy start - Dog ");
}
public void voice() {
System.out.println("gaw");
}
}
@Component ("person")
public class Person {
private Pet pet;
private String name;
public Pet getPet() {
return pet;
}
private int age;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("start setName");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
System.out.println("start setAge");
this.age = age;
}
public Person() {
}
@Resource
@Qualifier( "dog")
public void setPet ( Pet pet) {
this.pet = pet;
}
public void callYouPet() {
System.out.println("Hello, Pet");
pet.voice();
}
}
@Configuration
@ComponentScan ("org.example")
public class MyConfig {
}
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Dog dog = context.getBean("dog", Dog.class);
Person person = context.getBean("person", Person.class);
person.callYouPet();
// Car car = context.getBean(Car.class);
//car.drive("John");
// car.drive("Michel");
context.close();
}
}
Ответы (1 шт):
Автор решения: Elena
→ Ссылка
В итоге просто поигралась с зависимостями, и всё заработало.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.31</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.31</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>