Spring data Jpa Lanca @Autowired error and null pointer error

Asked

Viewed 213 times

-2

I’m using Spring Tool Suite to make an application, but when I try to release the website’s html data to the database, the relative service method will save and generate persistence returns java.lang.NullPointerException. Now, the data I receive is coherent, that is, it goes from html pro java without problems, but it gives this error when I invoke this part, including the application hangs if I put the method of saving out of Try-catch. Add @Autowired on top of the service parameter, there that gives error really, and hangs:

Description:

Field fazer in com.example.demo.Control.Homentroler required a bean of type 'Services.Servicos' that could not be found.

The Injection point has the following Annotations: - @org.springframework.Beans.factory.Annotation.Autowired(required=true)

Action:

Consider Defining a bean of type 'Services.Servicos' in your Configuration.

What can it be?

@Entity
public class Ficha implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //@Column(name = "id", unique = true)
public long id;

private String nome;

private String email;

private String sugestao;


public Ficha() {

}

public Ficha( @NotNull String nome, @NotNull String email, @NotNull String sugestao) {
    this.id = id;
    this.nome = nome;
    this.email = email;
    this.sugestao = sugestao;
}


/*GETTERS E SETTERS*/
}

Control:

@RestController
public class InicialControler {

//@Autowired
private Servicos fazer ;

@RequestMapping("/sugestoes")
public @ResponseBody ModelAndView mostrarSugestao(Ficha fichar){


    ModelAndView mostrar = new ModelAndView();
    mostrar.setViewName("sugestao");
    mostrar.addObject("fichar", fichar);
    Ficha fichando = new Ficha(fichar.getNome(), fichar.getEmail(), fichar.getSugestao());


    try {
        fazer.cadastrar(fichando);
//fazer.SaveFlush(fichando);
        System.out.println("be save" );
    }catch(Exception e) {
System.out.println( "erro ==> "  + e.getLocalizedMessage() + " " + e + " " +fichando.toString());
    }

    return mostrar;
}
}

Service:

@Service
public class Servicos implements GenericosServicos<Ficha, Long>   {

@Autowired
RepositorioDados repositar;

@Override
public Optional<Ficha> buscarPorId(Long id) {
    return repositar.findById(id);
}

@Override
public Ficha cadastrar(Ficha t) {

     return repositar.save(t);  
}

public void Save(Ficha t) {
    repositar.save(t);
}

@Override
public Ficha alterar(Long k, Ficha t) {

    // TODO Auto-generated method stub
    return null;
}

@Override
public List<Ficha> ListarTodos() {
    return repositar.findAll();
}

@Override
public void deletar(Long k) {
    repositar.deleteById(k);
}


}

Interface:

@Repository
@Transactional
public interface RepositorioDados extends JpaRepository<Ficha, Long> {

public Ficha save(Ficha user);

}

@SpringBootApplication
@EnableScheduling
@EnableAutoConfiguration
@EntityScan(basePackages = {"com.example.demo.model"})//nome do pacote aonde está a entidade
@EnableJpaRepositories(basePackages = {"DAO"})/nome do pacote aonde está o repositorio
public class PrimeSrpingApplication {

    public static void main(String[] args) {
        SpringApplication.run(PrimeSrpingApplication.class, args);
    }

}



<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>


<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>PrimeSrping</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

1 answer

0

To initially resolve your Nullpointerexception, you need to inject a Service reference using the annotation @Autowired spring.

@Autowired
private Servicos fazer;

To understand what Nullpointerexception is, click here

  • No, if I put @Autowired on top of the service instance, it gives this error:Description: Field fazer in com.example.demo.Control.Homebrowse required a bean of type 'Services.Servicos' that could not be found. The Injection point has the following Annotations: - @org.springframework.Beans.factory.Annotation.Autowired(required=true) Action: Consider Defining a bean of type 'Services.Servicos' in your Configuration. I wanted to know how to do this business right, I even instated Services, but it didn’t work

  • @Perfect Tim, the error you quoted now means that Spring was unable to identify a valid implementation of the Servicos interface (it is not yet the case to remove the @Autowired annotation). Are you using the ? Spring Framework or Spring Boot ? Have you edit the question again and put your respective Spring configuration?

  • Yes, I am using Spring Tool Suite and its settings. Now, I get a null pointer error when using this there, except if I put @Autowired on top of the service object, then it gives error and hangs.

  • Spring Tool Suite is an extension of the Eclipse IDE to work with the Spring framework. Reading your fonts now, I noticed that you are using the Spring Boot implementation. In its Primespringapplication.java class, note it with the annotation @Componentscan("PACKAGE-DO-SEUS-SERVICOS-AQUI"), at first it is this annotation that is missing for Spring to recognize the implementations of its services, don’t forget to keep the @Autowired I asked you to put in the previous comment.

  • There is no compiler error, but when I go to the browser to open the screen gives blank page error: Whitelabel Error Page This application has no Explicit Mapping for /error, so you are Seeing this as a fallback. There was an Unexpected error (type=Not Found, status=404). No message available. But it works normally, if I take Autowired from above the service object, and Componentscan from the Primespringapplication class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.