2

I've scanned the internet to find an example of how to use @Autowired private DataSource dataSource;. There are lots of places that say you can configure it using application.properties, but no full usage examples.

Update

@UsmanMutawakil

Where I've got to so far...

application.properties:

spring.datasource.url=jdbc:oracle:oci:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = IP_HOST)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = service_name)))
spring.datasource.username=myDBUsrName
spring.datasource.password=myDBPass
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

1st the Spring-Boot Application:

package br.com.empresa.solicitacaoprocedimento30302;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class Solicitacaoprocedimento30302Application {

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

2nd Servlet Initializer:

package br.com.empresa.solicitacaoprocedimento30302;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Solicitacaoprocedimento30302Application.class);
    }

}

Endpoint (jaxws):

package br.com.empresa.solicitacaoprocedimento30302;

import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import br.com.empresa.solicitacaoprocedimento30302.controller.TissSolicitacaoProcedimentoController;
import java.sql.SQLException;


@WebService(serviceName = "tissSolicitacaoProcedimento", portName = "tissSolicitacaoProcedimento_Port", endpointInterface = "br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissSolicitacaoProcedimentoPortType", targetNamespace = "http://www.ans.gov.br/tiss/ws/tipos/tisssolicitacaoprocedimento/v30302", wsdlLocation = "WEB-INF/wsdl/tissSolicitacaoProcedimentoV3_03_02.wsdl")
public class tissSolicitacaoProcedimentoWSEndpoint {

    @Autowired
    private TissSolicitacaoProcedimentoController tissSolicitacaoProcedimentoController;

    public br.gov.ans.padroes.tiss.schemas.AutorizacaoProcedimentoWS tissSolicitacaoProcedimentoOperation(br.gov.ans.padroes.tiss.schemas.SolicitacaoProcedimentoWS solicitacaoProcedimento) 
            throws br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissFault,
                   SQLException, Exception 
    {
        return tissSolicitacaoProcedimentoController.tissSolicitacaoProcedimentoOperation(solicitacaoProcedimento);
    }
}

Controller:

package br.com.empresa.solicitacaoprocedimento30302.controller;

import org.springframework.beans.factory.annotation.Autowired;
import br.gov.ans.padroes.tiss.schemas.AutorizacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.SolicitacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.ObjectFactory;
import br.com.example.solicitacaoprocedimento30302.auxiliar.ConfigVlr;
import java.sql.SQLException;

import org.springframework.stereotype.Controller;

@Controller("tissSolicitacaoProcedimentoController")
public class TissSolicitacaoProcedimentoController {

    @Autowired
    private ConfigVlr configVlr;

    public AutorizacaoProcedimentoWS tissSolicitacaoProcedimentoOperation(SolicitacaoProcedimentoWS solicitacaoProcedimento) throws SQLException, Exception 
    {
        ObjectFactory objFact = new ObjectFactory();

        AutorizacaoProcedimentoWS retAutorizacaoProcedimentoWS = objFact.createAutorizacaoProcedimentoWS();

        retAutorizacaoProcedimentoWS.setCabecalho(objFact.createAutorizacaoProcedimentoWSCabecalho());
        retAutorizacaoProcedimentoWS.setAutorizacaoProcedimento(objFact.createAutorizacaoProcedimentoWSAutorizacaoProcedimento());

        String item = configVlr.getValor("OWNER", "REQUIRE_LOGIN_WEB_SERVICE");

        retAutorizacaoProcedimentoWS.setHash("item=" + item);

        retAutorizacaoProcedimentoWS.setHash("tissSolicitacaoProcedimentoOperation() SQLException = " + sqlEx.getMessage() + "; class = " + sqlEx.getClass() + "; tissSolicitacaoProcedimentoOperation:GotTo = " + gotTo + "/nStack Trace:/n" + sqlEx.getStackTrace());

        return retAutorizacaoProcedimentoWS;
    }
}

Component:

package br.com.empresa.solicitacaoprocedimento30302.auxiliar;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.JDBCType;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("configVlr")
public class ConfigVlr
{
    @Autowired
    private DataSource dataSource;

    public String getValor(String owner, String variavel) throws SQLException, Exception 
    {
        String ret = null;
        Integer nErroProc = 0;
        String sErroProc = null;
        String call = "{ call OWNER.PCG_OWNER.CONFIG(?, ?, ?, ?, ?) }";


        Connection conn = dataSource.getConnection();

        CallableStatement cstmt = conn.prepareCall(call);

        cstmt.setString(1, owner);
        cstmt.setString(2, variavel);

        cstmt.registerOutParameter(3, JDBCType.VARCHAR, ret);
        cstmt.registerOutParameter(4, JDBCType.NUMERIC, nErroProc);
        cstmt.registerOutParameter(5, JDBCType.VARCHAR, sErroProc);

        cstmt.execute();

        if (nErroProc != 0) {
            throw new Exception("Proc error = " + nErroProc.toString() + " - " + sErroProc);
        }

        return ret;
    }
}

Configuration:

package br.com.empresa.solicitacaoprocedimento30302.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

import br.com.empresa.solicitacaoprocedimento30302.controller.TissSolicitacaoProcedimentoController;
import br.com.empresa.solicitacaoprocedimento30302.auxiliar.ConfigVlr;


@Configuration
public class ApplicationConfiguration {

    @Bean
    public TissSolicitacaoProcedimentoController tissSolicitacaoProcedimentoController() {
        return new TissSolicitacaoProcedimentoController();
    }

    @Bean
    public ConfigVlr configVlr() {
        return new ConfigVlr();
    }
}

This builds and deploys, but on the call to tissSolicitacaoProcedimentoController.tissSolicitacaoProcedimentoOperation(solicitacaoProcedimento); in the Endpoint, I get java.lang.NullPointerException:

2018-02-05 23:13:25.921 ERROR 16212 --- [nio-8090-exec-5] com.sun.xml.ws.server.sei.TieHandler     : null

java.lang.NullPointerException: null
    at br.com.empresa.solicitacaoprocedimento30302.tissSolicitacaoProcedimentoWSEndpoint.tissSolicitacaoProcedimentoOperation(tissSolicitacaoProcedimentoWSEndpoint.java:38) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at com.sun.xml.ws.util.Trampoline.invoke(MethodUtil.java:82) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at com.sun.xml.ws.util.MethodUtil.invoke(MethodUtil.java:107) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.server.MethodUtil.invoke(MethodUtil.java:64) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:250) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88) ~[jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.servlet.ServletAdapter.invokeAsync(ServletAdapter.java:225) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:161) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:197) [jaxws-rt-2.3.0.jar:2.3.0]
    at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:81) [jaxws-rt-2.3.0.jar:2.3.0]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [servlet-api.jar:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [catalina.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [catalina.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [catalina.jar:8.5.23]
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) [catalina.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [catalina.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [catalina.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-coyote.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-coyote.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-coyote.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

Any help is much appreciated.

Chrispy
  • 49
  • 1
  • 2
  • 9
  • And you think we can read the stacktrace from your mind? Please add it Ito your question. – M. Deinum Jan 20 '18 at 14:48
  • Thanks @M.Deinum, I've added the stacktrace of the error. – Chrispy Jan 20 '18 at 16:40
  • Would it help if I posted the POM as well? – Chrispy Jan 20 '18 at 19:46
  • @Chrispy I don't think its your POM but how your exposing the dataSource. I've added an updated example below. – Usman Mutawakil Jan 21 '18 at 15:33
  • An `@Autowired` field in Spring cannot be `null` if a dependency cannot be resolved it will fail at startup not at runtime. The problem is you are using Jax-ws (probably Apache CXF or something) and Spring isn't managing the bean. Your soap framework is and I highly doubt that it knows what to do with `@Autowired`. – M. Deinum Jan 22 '18 at 06:49
  • Thanks for the reply @M.Deinum. As I understand you, the class created by the the wsdl soap import, the `chrisMavenSpringBootWSDemoFromWSDL` class, isn't the right place to use the `@Autowired` annotation? Is there somewhere else in my web service that I can use it? – Chrispy Jan 22 '18 at 20:44
  • What you need to do is setup Spring integration for your SOAP implementation correctly. Most frameworks have Spring integration/support but that requires some additional configuration. – M. Deinum Jan 23 '18 at 07:19
  • @M.Deinum thanks for replying. I've scoured the internet from top to bottom and I couldn't find an up-to-date resolution to making the spring-boot appliction interact with the jax-ws generated webservice. Does anyone have a simple example, where I can use "@Autowired DataSource dataSource;" when the call chain comes from the WebService Endpoint generated by jax-ws? The link [29.1.2 Connection to a production database](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html) does nothing to help. Thanks in advance for any help. – Chrispy Feb 05 '18 at 21:49
  • @M.Deinum, hi, just to let you know: I am using the `org.codehaus.mojo` `jaxws-maven-plugin` `version 2.4.1` in my POM. You seem to be right, what I need is to connect the endpoint of the jaxws webservice so that it can see the `spring-boot` beans. I tried [this](https://stackoverflow.com/questions/5041154/how-to-make-an-webservice-spring-aware) but with no luck, I think it's too old. Thanks. – Chrispy Feb 08 '18 at 21:05

2 Answers2

2

I have come across 2 answers which led me to a solution:

  1. How can I access the ApplicationContext from within a JAX-WS web service?

  2. http://www.benchresources.net/metro-jax-ws-soap-based-web-service-using-top-down-approach-integrating-with-spring-framework

My final solution to this annoying problem:

application.properties:

spring.datasource.url=jdbc:oracle:oci:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = host_ip)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = service_name)))
spring.datasource.username=usr
spring.datasource.password=pass
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#Extra config
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

#jpa config.
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

1st the Spring-Boot Application (from spring-boot Inicializr):

package br.com.example.solicitacaoprocedimento30302;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Solicitacaoprocedimento30302Application {

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

}

2nd Servlet Initializer (from spring-boot Inicializr):

package br.com.example.solicitacaoprocedimento30302;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Solicitacaoprocedimento30302Application.class);
    }

}

Endpoint (jaxws import with alterations for the WebApplicationContext):

package br.com.example.solicitacaoprocedimento30302;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.stereotype.Service;

import br.gov.ans.padroes.tiss.schemas.AutorizacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.SolicitacaoProcedimentoWS;
import br.com.example.solicitacaoprocedimento30302.controller.TissSolicitacaoProcedimentoController;
import br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissFault;

@Service("tissSolicitacaoProcedimento")
@WebService(serviceName = "tissSolicitacaoProcedimento", 
            portName = "tissSolicitacaoProcedimento_Port", 
            endpointInterface = "br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissSolicitacaoProcedimentoPortType", 
            targetNamespace = "http://www.ans.gov.br/tiss/ws/tipos/tisssolicitacaoprocedimento/v30302", 
            wsdlLocation = "WEB-INF/wsdl/tissSolicitacaoProcedimentoV3_03_02.wsdl")
public class TissSolicitacaoProcedimentoWSEndpoint {

    @Autowired
    private TissSolicitacaoProcedimentoController tissSolicitacaoProcedimentoController;

    @Resource
    private WebServiceContext context;

    public AutorizacaoProcedimentoWS tissSolicitacaoProcedimentoOperation(SolicitacaoProcedimentoWS solicitacaoProcedimento) 
            throws TissFault
    {
        WebApplicationContext webApplicationContext = null;

        ServletContext servletContext = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);

        webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

        tissSolicitacaoProcedimentoController = webApplicationContext.getBean(TissSolicitacaoProcedimentoController.class);

        return tissSolicitacaoProcedimentoController.tissSolicitacaoProcedimentoOperation(solicitacaoProcedimento);
    }
}

Controller Interface:

package br.com.example.solicitacaoprocedimento30302.controller;

import br.gov.ans.padroes.tiss.schemas.AutorizacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.SolicitacaoProcedimentoWS;
import br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissFault;

public interface TissSolicitacaoProcedimentoController {

    public AutorizacaoProcedimentoWS tissSolicitacaoProcedimentoOperation(SolicitacaoProcedimentoWS solicitacaoProcedimento) throws TissFault;

}

Controller Implementation:

package br.com.example.solicitacaoprocedimento30302.controller;

import br.com.example.solicitacaoprocedimento30302.TissSolicitacaoProcedimentoWSEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import br.gov.ans.padroes.tiss.schemas.AutorizacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.SolicitacaoProcedimentoWS;
import br.gov.ans.padroes.tiss.schemas.ObjectFactory;
import br.com.example.solicitacaoprocedimento30302.dao.ConfigVlrDAO;
import br.gov.ans.tiss.ws.tipos.tisssolicitacaoprocedimento.v30302.TissFault;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.stereotype.Service;

@Service("tissSolicitacaoProcedimentoController")
public class TissSolicitacaoProcedimentoControllerImpl implements TissSolicitacaoProcedimentoController {

    @Autowired
    private ConfigVlrDAO configVlrDAO;

    public AutorizacaoProcedimentoWS tissSolicitacaoProcedimentoOperation(SolicitacaoProcedimentoWS solicitacaoProcedimento) throws TissFault 
    {
        ObjectFactory objFact = new ObjectFactory();

        AutorizacaoProcedimentoWS retAutorizacaoProcedimentoWS = objFact.createAutorizacaoProcedimentoWS();

        retAutorizacaoProcedimentoWS.setCabecalho(objFact.createAutorizacaoProcedimentoWSCabecalho());
        retAutorizacaoProcedimentoWS.setAutorizacaoProcedimento(objFact.createAutorizacaoProcedimentoWSAutorizacaoProcedimento());

        try 
        {
            String item = configVlrDAO.getValor("SIS", "OBRIGA_LOGIN_WEB_SERVICE");

            retAutorizacaoProcedimentoWS.setHash("item=" + item);

            return retAutorizacaoProcedimentoWS;
        } catch (SQLException sqlEx) {
            Logger.getLogger(TissSolicitacaoProcedimentoWSEndpoint.class.getName()).log(Level.SEVERE, null, sqlEx);
            throw new RuntimeException("Erro ao acessar o banco! " + sqlEx.getMessage(), sqlEx);
        } catch (Exception ex) {
            Logger.getLogger(TissSolicitacaoProcedimentoWSEndpoint.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException("Falha default: " + ex.getMessage(), ex);
        }

    }
}

Repository interface:

package br.com.example.solicitacaoprocedimento30302.dao;

import java.sql.SQLException;

public interface ConfigVlrDAO {

    public String getValor(String owner, String variavel) throws SQLException, Exception;

}

Repository Implementation:

package br.com.example.solicitacaoprocedimento30302.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.sql.SQLException;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.tomcat.jdbc.pool.DataSource;

@Repository("configVlrDAO")
public class ConfigVlrDAOImpl implements ConfigVlrDAO
{
    @Autowired
    private DataSource dataSource; // Don't need to create the DataSource bean!

    @Override
    public String getValor(String owner, String variavel) throws SQLException, Exception 
    {
        String ret = null;
        Integer nErroProc = 0;
        String sErroProc = null;
        String call = "{ call OWNER.PCG_OWNER.SPR_CONFIG_VLR(?, ?, ?, ?, ?) }";

        try (Connection conn = dataSource.getConnection())  
        {
            CallableStatement cstmt = conn.prepareCall(call);

            cstmt.setString(1, owner);
            cstmt.setString(2, variavel);

            cstmt.registerOutParameter(3, Types.VARCHAR);
            cstmt.registerOutParameter(4, Types.NUMERIC);
            cstmt.registerOutParameter(5, Types.VARCHAR);

            cstmt.execute();

            ret = cstmt.getString(3);
            nErroProc = cstmt.getInt(4);
            sErroProc = cstmt.getString(5);

            if (nErroProc != 0) {
                throw new Exception("Proc error = " + nErroProc.toString() + " - " + sErroProc);
            }
        }

        return ret;
    }
}
Chrispy
  • 49
  • 1
  • 2
  • 9
0

You have no DataSource bean. If you had a datasource been available in the Spring environment then it would be autowired into that implementing interface location. Configure a dataSource bean in your configuration class (or XML if your brave) and this should work. Your application.proprties file is only exposing values that can be used elsewhere in your application like $spring.datasource.url instead of typing the actual URL.

You can use the properties of your application.properties file inside your datasource bean creation logic but just adding those values to applicaton.properties does not create the needed datasource bean.

XML Example:

<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
   <property name="driverClassName" value="${dataSource.driverClassName}" />
       <property name="url" value="${dataSource.url}" />
       <property name="username" value="${dataSource.username}" />
       <property name="password" value="${dataSource.password}" />
       <property name="initialSize" value="10"/>
   <property name="maxActive" value="400"/>
   <property name="testWhileIdle" value="true"/>
   <property name="validationQuery" value="${dataSource.validationQuery}"/>
   <property name="validationInterval" value="600000"/>
   <property name="timeBetweenEvictionRunsMillis" value="600000"/>
   <property name="minIdle" value="10"/>
   <property name="maxIdle" value="100"/>
   <property name="testOnBorrow" value="true"/>
   <property name="removeAbandoned" value="true"/>
   <property name="connectionProperties" value="encrypt=true;TrustServerCertificate=true"/>
</bean>

You can achieve the same without XML in your @Configuration class if your using one. Inside that class you can define the same as above using Java instead of XML and where you need explicit values you can reference your application.properties using reference values such as ${blah}.

@Configuration Example

@Configuration    
public class ApplicationConfig {

    //Return connection to the DB, or atleast an abstracted connection to the connection pool (C3P0)
    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //Configure your dataSource here
        return dataSource;
    }


}
Usman Mutawakil
  • 4,993
  • 9
  • 43
  • 80
  • Usman Mutawakil, thanks for the response. I was just checking stackoverflow with a some of the annotations involved in my question and your answer and I found [this](https://stackoverflow.com/questions/37550911/spring-boot-autowiring-a-datasource-bean) which seems to suggest that when using the `@SpringBootApplication` annotation in conjunction with `application.properties`, it should "automatically autowire a DataSource Bean from these properties." – Chrispy Jan 21 '18 at 21:06
  • Also, other places in SO say that with this automatic configuration I should not use `new Datasource` in my code, just the `@Autowired Datasource datasource`, otherwise the automatic bean will not be created. This mostly from the spring-boot docs. – Chrispy Jan 21 '18 at 21:13
  • Here's the link to the documentos: [29.1.2 Connection to a production database](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html) which states: "If you define your own DataSource bean, auto-configuration will not occur" – Chrispy Jan 21 '18 at 21:38
  • Interesting. And your application.properties file is on the classpath? – Usman Mutawakil Jan 21 '18 at 21:47
  • Usman Mutawakil - It's in the `chrisMavenSpringBootWSDemoProject\src\main\resources` directory. BTW I can't use your name in the comment using `@`, it keeps disappearing! – Chrispy Jan 21 '18 at 23:58
  • thanks for your help. I'm ready to give up on the spring-boot jax-ws integration. Can you suggest how to link the dataSource bean to the embedded tomcat Connection Pool? – Chrispy Feb 05 '18 at 22:06
  • Before we throw in the towel can I ask if your using a "@Configuration" class anywhere? The approach I showed up here requires that but going through the docs Spring-Boot also seems to require it. On your config class try using @Configuration and "@EnableAutoConfiguration" – Usman Mutawakil Feb 05 '18 at 22:43
  • Supporting link -> https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-configuration-classes.html – Usman Mutawakil Feb 05 '18 at 22:44
  • I am using `@SpringBootApplication`, which the spring-boot initializr generates in the `br.com.saofrancisco.solicitacaoprocedimento30302` package, which is supposed to be [used as a shortcut of @EnableAutoConfiguration, @ComponentScan and @Configuration](http://www.logicbig.com/tutorials/spring-framework/spring-boot/auto-config-mechanism/) in any annotations below the package. I have a `@Configuration` in `br.com.saofrancisco.solicitacaoprocedimento30302.configuration` package and I have 2 classes that I want to autoconfigure, but they are being called by `@WebService` class. – Chrispy Feb 05 '18 at 23:56
  • They seem to be working, but I'm getting an error when trying to load the dataSource from the `application.properties` file. It's an oracle driver: `Cannot load driver class: oracle.jdbc.OracleDriver`. I'm still investigating this. – Chrispy Feb 06 '18 at 00:07
  • l Solved the error of the Oracle Driver by adding ` com.oracle ojdbc7 12.1.0.2 ` to the POM file. Now I'm having the problem of the beans being null again. I will add an Answer so you can see where I am... – Chrispy Feb 06 '18 at 00:38
  • I think the problem is that I'm trying to call spring-boot beans from a jaxws generated `@WebService` and I can't find a solution anywhere that integrates the webservice into spring-boot. – Chrispy Feb 06 '18 at 15:14