Java Spring - Repository returns Null

2

This is my ApiKey class:

    @Entity
@Table(name="API_KEYS", schema="DEMO_PIMS")
@JsonIgnoreProperties(allowGetters=true)
public class ApiKey implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="ID_REG")
    private Integer id;

    @Column(name="SERVICE")
    private String service;

    @Column(name="KEY")
    private String Key;
(... Getters and Setters...)

This is the repository:

 @Repository
public interface ApiKeyRepository extends JpaRepository<ApiKey, Integer>{   

    @Query("SELECT a FROM ApiKey a WHERE a.service = ?1")
    ApiKey getByservice(String nome);

}

I'm using the class ClimaTempoAPI.java which has the following structure:

  public class ClimaTempoAPI {

    @Autowired
    ApiKeyRepository apiKeyRepository;

    public JSONObject RequestWeather(String weatherEndpoint) throws IOException, JSONException, ParseException {


        ApiKey appToken = apiKeyRepository.getByservice("climaTempo2");


        URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + appToken.getKey());

        return ConnectionJson.returnJson(weatherDomain, true);

    }

}

But when calling the getByservice method ("weatherTime2") it throws a Null Pointer Exception exception.

What am I doing wrong that does not work?

I've seen other answers in StackOverflow, but what they put as a solution did not work for me:

StackOverflow in English - I tested it by adding @Service, @Configurable, and @Component - It did not work out

StackOverflow in English - @Service, @Transactional

    
asked by anonymous 27.06.2018 / 16:16

1 answer

2

I do not know why, but only resolved when I passed the code to the ClimateTempoController class.

ClimaTempoController.java:

    @RestController
    @RequestMapping("/cockpit")
    @CrossOrigin(origins="*", maxAge=3600)
    public class ClimaTempoController { 

        @Autowired
        ApiKeyRepository apiKeyRepository;  

        @RequestMapping(value= "/clima/{nomeCidade}/{ufCidade}/agora",  method = {RequestMethod.GET})
        public ResponseEntity<Clima> getClimaAgoraByNomeCidade(@PathVariable etc etc..) {
            (...)
            ApiKey appToken = apiKeyRepository.getByservice("climaTempo2");
            climaCidade = ct.RequestWeather(weatherEndpoint, appToken.getKey());

        }
     }

The same code only in a @RestController class

    
28.06.2018 / 13:17