Please help ;) main can't find bean Personserviceimp ???????????????????????????????????
Main
package spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class Main {
@Autowired
static PersonServiceImpl service;
public static void main(String[] args){
System.out.println(service.findByName("Valera").getAge());
}
}
PersonService
package spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonServiceImpl implements PersonService{
private final PersonDao dao;
@Autowired
public PersonServiceImpl(PersonDao dao) {
this.dao = dao;
}
@Override
public Person findByName(String name) {
return dao.findByName(name);
}
}
PersonDao
package spring;
import org.springframework.stereotype.Repository;
@Repository
public class PersonDao implements IPersonDAO{
public Person findByName(String name) {
return new Person(name, 18);
}
}
Person
package spring;
public class Person {
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring2</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
</dependencies>
</project>
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "spring.RersonServiceImpl.findByName(String)" because "spring.Main.service" is null at spring.Main.main(Main.java:12)
I did this but I still get null
@ComponentScan
@Component("Main")
public class Main {
private static PersonServiceImpl service;
@Autowired
public Main(PersonServiceImpl service) {
Main.service = service;
}
public static void main(String[] args){
System.out.println(service.findByName("Valera").getAge());
}
}
and so
public class Main {
private static RersonServiceImpl service_;
@Autowired
private RersonServiceImpl service;
@PostConstruct
private void init() {
service_ = this.service;
}
public static void main(String[] args){
System.out.println(service_.findByName("Valera").getAge());
}
}