Autowired mapper in service is null.
There is mapper - VaMapper.java
#Mapper
#Repository
public interface VaMapper {
int getSiteVa(ParameterMap param) throws Exception;
}
There is service class. - VaService.java
#Service
public class VaService {
private static final Logger logger = LoggerFactory.getLogger(VaService.class);
#Autowired
public VaMapper vaMapper; //This mapper is null
public void handlVaInfo(JSONObject vaObj) throws Exception{
String vaHost = vaObj.get("vaHost").toString();
System.out.println("vaHost:"+vaHost);
int a = vaMapper.getSiteVa(new ParameterMap());
}
And I want to use this service on below class. - SimpleEchoSocket.java
#WebSocket(maxTextMessageSize = 64 * 1024)
public class SimpleEchoSocket{
public VaServiceva vaService(){
return new VaService();
}
#OnWebSocketMessage
public void onMessageBuffer(Session session, byte[] byteArray, int offset, int length) throws Exception {
System.out.println("onMessageBuffer");
String vaHost = session.getRemoteAddress().toString().replaceAll("/", "");
System.out.println("vaHost:"+vaHost);
int thisIdx = -1;
JSONObject thisObj = null;
for(int i=0; i<vaArray.size(); i++){
JSONObject vaObj = (JSONObject) vaArray.get(i);
if(vaObj.get("vaHost").toString().equals(vaHost)){
vaObj.put("plateImg", byteArray);
thisIdx = i;
thisObj = vaObj;
break;
}
}
if(thisIdx != -1){
vaArray.remove(thisIdx);
vaService().handlVaInfo(thisObj);
}
}
}
However NullPointerExcpetion occured like below.
java.lang.NullPointerException: Cannot invoke "com.iimp.pom.mapper.va.VaMapper.getSiteVa(com.iimp.pom.util.ParameterMap)" because "this.vaMapper" is null
at com.iimp.pom.service.va.VaService.getSiteVa(VaService.java:50)
at com.iimp.pom.va.VaProcessor.handlVaInfo(VaProcessor.java:44)
at com.iimp.pom.socket.SimpleEchoSocket.onMessageBuffer(SimpleEchoSocket.java:118)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.eclipse.jetty.websocket.common.events.annotated.CallableMethod.call(CallableMethod.java:70)
at org.eclipse.jetty.websocket.common.events.annotated.OptionalSessionCallableMethod.call(OptionalSessionCallableMethod.java:68)
at org.eclipse.jetty.websocket.common.events.JettyAnnotatedEventDriver.onBinaryMessage(JettyAnnotatedEventDriver.java:143)
at org.eclipse.jetty.websocket.common.message.SimpleBinaryMessage.messageComplete(SimpleBinaryMessage.java:75)
at org.eclipse.jetty.websocket.common.events.AbstractEventDriver.appendMessage(AbstractEventDriver.java:67)
at org.eclipse.jetty.websocket.common.events.JettyAnnotatedEventDriver.onBinaryFrame(JettyAnnotatedEventDriver.java:130)
at org.eclipse.jetty.websocket.common.events.AbstractEventDriver.incomingFrame(AbstractEventDriver.java:147)
at org.eclipse.jetty.websocket.common.WebSocketSession.incomingFrame(WebSocketSession.java:326)
at org.eclipse.jetty.websocket.common.extensions.ExtensionStack.incomingFrame(ExtensionStack.java:202)
at org.eclipse.jetty.websocket.common.Parser.notifyFrame(Parser.java:225)
at org.eclipse.jetty.websocket.common.Parser.parseSingleFrame(Parser.java:259)
at org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection.onFillable(AbstractWebSocketConnection.java:459)
at org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection.onFillable(AbstractWebSocketConnection.java:440)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105)
at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:336)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:313)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:171)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:135)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:882)
at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1036)
at java.base/java.lang.Thread.run(Thread.java:831)
...
As Denuim said, SimpleEchoSocket is managed by jetty not springboot.
But I think I succeed to load VaService on SimpleEchoSocket.
I changed code for load mapper instead of autowired.
However VaMapper is abstract, so I can't load mapper just like that.
How can I load vaMapper on VaService?
Please help me.
Thank you all.
Related
I have a JPA repository method that is throwing an exception for a null value. I don't understand why its throwing the exception because it can be null in the database table. I don't believe its reaching the persistence stuff yet, but rather exception is be thrown before getting there.
Unfortunately I have to disguise a lot of the coding (plus I simplified by removing lots of params for readability). I would be grateful for any insights.
Here is key part of exception:
java.lang.IllegalArgumentException: Parameter a_e_mark in CMarkRepository.insertCMark must not be null!
at org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy142.insertCMark(Unknown Source)
at service.SMarkService.postCMark(SMarkService.java:213)
at controller.SMarkController.postCMark(SMarkController.java:259)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.....
Here is the important part of calling code:
public int postCMark (CMark cMark) {
CMark cm = null;
int status = 0;
try {
status = cMarkRepository.insertCMark(cMark.getCFk(), stringListToStringArray(cMark.getAEMark())));
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}
private String stringListToStringArray(List<String> stringList) {
StringListConverterCommaDelim stringListConverterCommaDelim = new StringListConverterCommaDelim();
return stringListConverterCommaDelim.convertToDatabaseColumn(stringList);
}
Here is the converter:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
#Converter
public class StringListConverterCommaDelim implements AttributeConverter<List<String>, String>
{
private static final String SPLIT_CHAR = ",";
#Override
public String convertToDatabaseColumn(List<String> stringList) {
String splitString = null;
if(stringList != null) {
splitString = String.join(SPLIT_CHAR, stringList);
splitString = "{" + splitString + "}";
}
return splitString;
}
#Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
here is the repo:
public interface CMarkRepository extends JpaRepository <CMark, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, a_e_mark) values(:c_fk, :a_e_mark\\:\\:character varying[])", nativeQuery = true)
int insertClassMark(#Param("c_fk") String classification_fk, #Param("a_e_mark") String a_e_mark);
}
ok, figured it out. Just by adding #Nullable to each parameter directly its solved:
public interface CMarkRepository extends JpaRepository <CMark, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, a_e_mark) values(:c_fk, :a_e_mark\\:\\:character varying[])", nativeQuery = true)
int insertClassMark(#Param("c_fk") #Nullable String classification_fk, #Param("a_e_mark") #Nullable String a_e_mark);
}
I'm running a service and it works perfectly when it returns some entidade. But when it doesn't find any, I get the following error:
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 BAD REQUEST: [{
"entidades": [],
"saida": "" rua bandeirantes, 1578 - bairro: cent... (19970 bytes)]
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:101)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:818)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:710)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:467)
at br.mp.mpf.cened01.cargaIaRJ.RJServico.executarServico(RJServico.java:953)
at br.mp.mpf.cened01.cargaIaRJ.RJServico.executarServicoByPagina(RJServico.java:857)
at br.mp.mpf.cened01.cargaIaRJ.RJServico.executarComPaginacao(RJServico.java:752)
at br.mp.mpf.cened01.cargaIaRJ.RJApplication.lambda$0(RJApplication.java:52)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300)
at br.mp.mpf.cened01.cargaIaRJ.RJApplication.main(RJApplication.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
private RetornoServicoDto executarServico(String sentenca)
throws Exception {
RetornoServicoDto retornoServico = new RetornoServicoDto();
final String sentencaOri = sentenca;
RestTemplate restTemplate = new RestTemplate();
final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator();
while (iterator.hasNext()) {
final HttpMessageConverter<?> converter = iterator.next();
if (converter instanceof StringHttpMessageConverter) {
iterator.remove();
}
}
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
try {
ResponseEntity<RetornoServicoDto> responseEntity =
restTemplate.postForEntity(Constantes.SERVICO_URL,
sentencaOri, RetornoServicoDto.class);
retornoServico = responseEntity.getBody();
} catch (Exception e) {
e.printStackTrace();
}
return retornoServico;
}
#Data
public class RetornoServicoDto {
private List<EntidadeDto> entidades;
private String saida;
private String status;
}
#Data
public class EntidadeDto {
private String entidade;
private int id;
private PosicaoDto posicao;
private String texto;
}
What to do to work even when the entities list returns []?
Based on what I see from your log, your response object starts with an "[{..." so probably your server side is returning an list of RetornoServicoDto, not a single object that what you are asking the request for, since your problem is a bad request, would be great to see the service side that process the request to understand better.
Gary Russell helped me some time ago with the following 'DynamicTcpServer' flow (see Building a TCP/IP server with SI's dynamic flow registration) having now a message service injected which gets the message to send as soon as a client connects:
public class DynamicTcpServer implements TcpServer {
#Autowired
private IntegrationFlowContext flowContext;
#Autowired
private ApplicationContext appContext;
private final Map<String, IntegrationFlowRegistration> registrations = new HashMap<>();
private final Map<String, String> clients = new ConcurrentHashMap<>();
private final Map<String, TcpServerSpec> sockets;
private final MessageService messenger;
#Autowired
public DynamicTcpServer(MessageService messenger, Map<String, TcpServerSpec> sockets) {
this.messenger = messenger;
this.sockets = sockets;
}
#Override
public void start(String context) {
start(context, sockets.get(context).getPort());
}
#Override
public void start(String context, int port) {
if (this.registrations.containsKey(context)) {
/* already running */
}
else {
TcpServerConnectionFactorySpec server = Tcp.netServer(port).id(context).serializer(TcpCodecs.lf());
server.get().registerListener(msg -> false); // dummy listener so the accept thread doesn't exit
IntegrationFlow flow = f -> f.handle(Tcp.outboundAdapter(server));
this.registrations.put(context, flowContext.registration(flow).register());
}
}
#Override
public Set<String> running() {
return registrations.keySet();
}
#Override
public void stop(String context) {
IntegrationFlowRegistration registration = this.registrations.remove(context);
if (registration != null) {
registration.destroy();
}
}
#EventListener
public void connect(TcpConnectionOpenEvent event) {
String connectionId = event.getConnectionId();
this.clients.put(connectionId, event.getConnectionFactoryName());
}
#EventListener
public void closed(TcpConnectionCloseEvent event) {
this.clients.remove(event.getConnectionId());
}
#EventListener
public void listening(TcpConnectionServerListeningEvent event) {
}
#Scheduled(
fixedDelayString = "${com.harry.potter.scheduler.fixed-delay}",
initialDelayString = "${com.harry.potter.scheduler.initial-delay}"
)
public void sender() {
this.clients.forEach((connectId, context) -> {
IntegrationFlowRegistration register = registrations.get(context);
if (register != null) {
try {
while (true) {
List<ServerMessage> msgs = messenger.getMessagesToSend(sockets.get(context));
msgs.stream().forEach(msg ->
register.getMessagingTemplate().send(
MessageBuilder.withPayload(msg)
.setHeader(IpHeaders.CONNECTION_ID, connectId).build()));
}
}
catch (NoMessageToSendException nm) {
appContext.getBean(context, TcpNetServerConnectionFactory.class)
.closeConnection(connectId);
}
}
});
}
}
The message service returns a Java object 'com.harry.potter.entity.ServerMessage' to be sent.
So I assume I have to add some other kind of converter at '.serializer(TcpCodecs.lf())' because I got an exception saying:
2022-04-17 04:00:45.729 DEBUG [] --- [pool-283-thread-1] c.l.c.c.cas.service.DynamicTcpServer : sender: send 1 messages to potter1
2022-04-17 04:00:45.738 DEBUG [] --- [pool-283-thread-1] c.l.c.c.c.service.DynamicTcpServer : closed event=TcpConnectionCloseEvent [source=TcpNetConnection:harry.potter.de:56746:17584:76adefe0-0881-4e4b-be2b-0ced47f950ae], [factory=potter1, connectionId=harry.potter.de:56746:17584:76adefe0-0881-4e4b-be2b-0ced47f950ae] **CLOSED**
2022-04-17 04:00:45.740 ERROR [] --- [pool-283-thread-1] o.s.i.ip.tcp.TcpSendingMessageHandler : Error sending message
org.springframework.messaging.MessagingException: Send Failed; nested exception is java.lang.IllegalArgumentException: When using a byte array serializer, the socket mapper expects either a byte array or String payload, but received: class com.harry.potter.entity.ServerMessage
at org.springframework.integration.ip.tcp.connection.TcpNetConnection.send(TcpNetConnection.java:118)
at org.springframework.integration.ip.tcp.TcpSendingMessageHandler.handleMessageAsServer(TcpSendingMessageHandler.java:119)
at org.springframework.integration.ip.tcp.TcpSendingMessageHandler.handleMessageInternal(TcpSendingMessageHandler.java:103)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:62)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:570)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:520)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:99)
at com.harry.potter.service.DynamicTcpServer.lambda$sender$2(DynamicTcpServer.java:125)
at com.harry.potter.service.DynamicTcpServer$$Lambda$40600/0x000000006f511b08.accept(Unknown Source)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at com.harry.potter.service.DynamicTcpServer.lambda$sender$3(DynamicTcpServer.java:124)
at com.harry.potter.service.DynamicTcpServer$$Lambda$40552/0x000000003344f3b0.accept(Unknown Source)
at java.base/java.util.concurrent.ConcurrentHashMap.forEach(ConcurrentHashMap.java:1603)
at com.harry.potter.service.DynamicTcpServer.sender(DynamicTcpServer.java:115)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:884)
Caused by: java.lang.IllegalArgumentException: When using a byte array serializer, the socket mapper expects either a byte array or String payload, but received: class com.harry.potter.entity.ServerMessage
at org.springframework.integration.ip.tcp.connection.TcpMessageMapper.getPayloadAsBytes(TcpMessageMapper.java:277)
at org.springframework.integration.ip.tcp.connection.TcpMessageMapper.fromMessage(TcpMessageMapper.java:252)
at org.springframework.integration.ip.tcp.connection.TcpNetConnection.send(TcpNetConnection.java:111)
... 34 common frames omitted
Which converter (serializer) do I have to use and how to plug it in my DynamicTcpServer exactly?
EDIT 1
The message service messenger returns a Java object 'com.harry.potter.entity.ServerMessage' to be sent. The ServerMessage contains an int field holding the message length and a String field holding the message text:
public class ServerMessage implements Serializable {
private static final long serialVersionUID = -1L;
private int len;
private String message;
/* getters & setters */
}
I am trying to migrate from a C/C++ function which writes the C Struct
struct C_MSG
{
int len; /* Length field */
char text[MAX_MSG_LEN]; /* Data field */
} c_msg;
to a consumer using the C Socket library send function writing a given number of bytes (length of text + 4) from the given memory address to the given TCP/IP socket.
I am looking for a Transformer to prepare the same binary content for the message consumer. Otherwise the consumer will not be able to cope with the message.
Following the comments and looking at the GenericTransformer<S, T> the transformation could be done in a single Lambda expression. The source of the transformation would be an object of the ServerMessage? The result should be an array of Bytes using Spring's utility:
.transform(s -> SerializationUtils.serialize(s))
Will the Lambda expression be that one? Perhaps do I need a custom Transformer - to have more control over the serializing process in case my consumer expects Intel resp. Motorola byte order - with implementing a specific interface? Which one? Perhaps there is a much easier solution?
You need to think about .transform() before that .handle(Tcp.outboundAdapter(server)); to convert your ServerMessage to byte[] or String. That's what is expected in the TcpMessageMapper by default.
Of course I could recommend you to look into the mapper(TcpMessageMapper mapper) option of the Tcp.netServer() and its bytesMessageMapper property, but the outcome would be just the same.
when spring boot first startup, jooq works well.
but if i make change to code and after spring boot context refreshed,
then i stucked in trouble with class cast exception.
the problem is cast exception on same class.
my boot conf is :
#Autowired
private DataSource dataSource;
public ExecuteListener exceptionTransformer() {
return new DefaultExecuteListener() {
private static final long serialVersionUID = 1L;
#Override
public void exception(ExecuteContext context) {
SQLDialect dialect = context.configuration().dialect();
SQLExceptionTranslator translator = (dialect != null)
? new SQLErrorCodeSQLExceptionTranslator(dialect.name())
: new SQLStateSQLExceptionTranslator();
context.exception(
translator.translate("jOOQ", context.sql(), context.sqlException()));
}
};
}
#Primary
#Bean
public DefaultDSLContext dsl() {
return new DefaultDSLContext(configuration());
}
public DataSourceConnectionProvider connectionProvider() {
return new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource));
}
public DefaultConfiguration configuration() {
DefaultConfiguration configuration = new DefaultConfiguration();
configuration.set(connectionProvider());
configuration.set(new DefaultExecuteListenerProvider(exceptionTransformer()));
configuration.set(SQLDialect.MYSQL);
// #formatter:off
configuration.set(
new Settings()
.withExecuteLogging(true)
.withRenderFormatted(true)
);
// #formatter:on
configuration.set(SfmRecordMapperProviderFactory.newInstance().ignorePropertyNotFound().newProvider());
return configuration;
}
query code is :
User user = dsl.select()
.from(USER)
.where(USER.USER_ID.eq(id)).fetchOneInto(User.class);
admin.domain.User is:
#Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String userId;
#JsonIgnore
private String pswd;
private String name;
private String useYn;
private Timestamp registDatetime;
private Timestamp updateDatetime;
}
stack trace is :
java.lang.ClassCastException: admin.domain.User cannot be cast to admin.domain.User
at admin.dao.UserDao.getUserByIdWithRoles(UserDao.java:123)
at admin.dao.UserDao$$FastClassBySpringCGLIB$$f7b71f39.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
what is my fault?
Do you have spring boot automatic restart enabled?
This look likes it, you could try:
to run without the devtools (https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart-disable)
add the correct path to your live reload (
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart-additional-paths and https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-customizing-classload )
:)
I'm quite new to SpringBoot. I have created a sample application with a service class.
Below is my SpringBootApplication class
#SpringBootApplication
public class SampleApplication {
#Autowired
static AWSService awsService;
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
awsService.getCertificate(); // Getting an NPE at this point
}
}
The AWSService class
#Service
public class AWSService {
public AWSService() {
}
private final Log log = new Log(getClass().getSimpleName());
public void getCertificate() {
String accessKey="";
String secretKey="";
try {
Scanner awsCredentials = new Scanner(new File(Constants.AWS_CREDENTIALS));
accessKey=awsCredentials.next();
secretKey=awsCredentials.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e.getMessage());
}
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey,secretKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(
new AWSStaticCredentialsProvider(basicAWSCredentials)).build();
S3Object s3object = s3Client.getObject(
new GetObjectRequest(Constants.S3_BUCKET_NAME, Constants.S3_KEY_NAME));
String temporaryCertificatePath = storeCertificate(s3object);
Constants.setKeyStoreFile(temporaryCertificatePath);
}
private String storeCertificate(S3Object s3Object) {
try {
File certificate = File.createTempFile("signingKey",".p12");
OutputStream outputStream = new FileOutputStream(certificate);
byte buffer [] = IOUtils.toByteArray(s3Object.getObjectContent());
outputStream.write(buffer);
certificate.deleteOnExit();
return certificate.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
}
return null;
}
}
Following is the error I'm getting
Exception in thread "main" java.lang.NullPointerException
2017-02-27 13:24:04.023 at in.juspay.SampleApplication.main(SampleApplication.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
INFO at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
798 at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
I have Autowired the service in my application class, yet I'm getting a NullPointerException. If I understand Spring's #Service properly, the #Autowire should take care of the initialization of the object. Why then, am I getting an NPE at that point?
You cannot autowire static fields. Use application context to reach it.
Can you use #Autowired with static fields?
Very basic thing, static fields gets priority even before bean creation.
That's why you can use static keyword to get a access of an instance.
refer this also Getting java.lang.NullPointerException when calling Method.invoke