Ribbon LB / OAuth2RestTemplate - spring-boot

I'm trying to invoke the load balancer to get access to a service instance in order to build the OAuth2RestTemplate access token uri within my configuration class, but for some reason I keep getting exceptions when the bean is instantiated. Has anyone come across this issue before? Or perhaps may have some insight?
Factory method 'restTemplate' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate ILoadBalancer for service: service
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource [com/apop/services/config/rest/RestConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.OAuth2RestTemplate]: Factory method 'serviceRestTemplate' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate ILoadBalancer for service: service
Also here are my service and configuration classes:
#Service
public class ServiceIntegration implements Service, Serializable {
#Resource(name = "serviceRestTemplate")
OAuth2RestTemplate serviceRestTemplate;
#Autowired
private LoadBalancerClient balancerClient;
#Value("${service}")
private String service;
private ResponseExceptionHelper responseExceptionHelper = new ResponseExceptionHelper();
public ResponseExceptionHelper getResponseExceptionHelper() {
return responseExceptionHelper;
}
public void setResponseExceptionHelper(
ResponseExceptionHelper responseExceptionHelper) {
this.responseExceptionHelper = responseExceptionHelper;
}
/**
* #param payload
* #param path
* #param method
* #return
* #throws ResponseException
*/
private String execute(OAuth2RestTemplate restTemplate, String endPoint, String payload, HttpMethod method)
throws ResponseException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
String response = null;
try {
ServiceInstance serviceInstance = balancerClient.choose(service);
String uri = String.format("http://%s:%s/%s", serviceInstance.getHost(), serviceInstance.getPort(), service) + endPoint;
ResponseEntity<String> responseEntity = restTemplate.exchange(uri, method, requestEntity, String.class);
if (responseEntity != null) {
response = responseEntity.getBody();
}
} catch (Exception e) {
logger.error(error, e);
throw e;
}
logger.info(response);
return response;
}
}
Config:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class RestConfiguration {
#Value("${service}")
private String service;
#Value("${token.service.endpoint}")
private String tokenServiceEndpoint;
#Value("${clientId}")
private String clientId;
#Value("${clientSecret}")
private String clientSecret;
#Value("${grant}")
private String grant;
#Autowired
private LoadBalancerClient balancerClient;
#Bean
public OAuth2RestTemplate serviceRestTemplate() {
ClientCredentialsResourceDetails resources = getClientDetails();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resources, new DefaultOAuth2ClientContext());
return restTemplate;
}
public ClientCredentialsResourceDetails getClientDetails() {
ServiceInstance serviceInstance = balancerClient.choose(service);
String uri = String.format("http://%s:%s/%s", serviceInstance.getHost(), serviceInstance.getPort(), legacyService) + tokenServiceEndpoint;
ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
resource.setAccessTokenUri(uri);
resource.setClientSecret(clientId);
resource.setClientId(clientSecret);
resource.setGrantType(grant);
return resource;
}
}

You are trying to do service discovery in #Bean definition (so super early) before the service catalog is available. It would be better to use a RibbonInterceptor in an otherwise normal OAuth2RestTemplate (like in the RibbonAutoConfiguration).

Related

java.time.format.DateTimeParseException handling in OpenFeign

I have multiple services, so I am using OpenFeign client like this:
#FeignClient(name = "identity-service")
public interface IdentityServiceClient {
#RequestMapping(method = RequestMethod.GET, value = "/validate", produces = MediaType.APPLICATION_JSON_VALUE)
boolean validateId(#RequestParam String id);
}
I use a Feign Decoder:
#Component
public class FeignErrorDecoder implements ErrorDecoder {
Environment environment;
#Autowired
Jackson2ObjectMapperBuilder mapperBuilder;
#Override
public Exception decode(String methodKey, Response response) {
ExceptionMessage message = new ExceptionMessage();
try (InputStream bodyIs = response.body().asInputStream()) {
ObjectMapper mapper = mapperBuilder.build();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_WITH_CONTEXT_TIME_ZONE);
message = mapper.readValue(bodyIs, ExceptionMessage.class);
} catch (IOException e) {
return new Exception(e.getMessage());
}
switch (response.status()) {
case 400:
return new ResponseStatusException(HttpStatus.BAD_REQUEST, message.getMessage() != null ? message.getMessage() : "Bad Request");
case 404:
return new ResponseStatusException(HttpStatus.NOT_FOUND, message.getMessage() != null ? message.getMessage() : "Not found");
default:
return errorDecoder.decode(methodKey, response);
}
}
I am trying to map the error into a custom error message for visibility:
public class ExceptionMessage {
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
private LocalDateTime timestamp;
private HttpStatus status;
private String error;
private String message;
private String path;
}
However, I get consistent error that I haven't been able to work around:
2022-08-02 17:05:17.206 ERROR 87600 --- [o-auto-1-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException] with root cause
java.lang.Exception: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-08-02T23:05:09.303+00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-08-02T23:05:09.303+00:00' could not be parsed at index 19
I have to confess I have never seen that particular datetime format '2022-08-02T23:05:09.303+00:00' before, where does that come from?

Mock LocalDate.now() and LocalTime.now() for testing scope

I need to mock the two static methods LocalDate.now() and LocalTime.now() in a testing class.
I'm using PowerMock but I receive this error when I try to run the test:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class javax.xml.transform.FactoryFinder
I had try to create a #Bean of RestTemplate.class inside the test class and configuration class but the error persists.
I have this error only if I run the test with PowerMockRunner.class. If I try to run it with SpringRunner.class everything is fine but I can't mock the LocalDate and LocalTime.
This is my Test class:
#PrepareForTest(LocalDate.class)
#RunWith(PowerMockRunner.class)
#SpringBootTest(webEnvironment = RANDOM_PORT, classes = ChallengeApplication.class)
#ActiveProfiles("test")
public class MockTest {
#Autowired
private TestRestTemplate restTemplate;
private URL base;
#LocalServerPort
int port;
User user = new User("user", "password", "user#test.com");
HttpEntity<User> userRequest = new HttpEntity<>(user);
Mock mock = new Mock(new BigDecimal(20));
HttpEntity<Mock> request = new HttpEntity<>(mock );
#Before
public void setUp() throws MalformedURLException {
restTemplate = new TestRestTemplate();
base = new URL("http://localhost:" + port + "/mock/users");
restTemplate.postForEntity(base.toString(), userRequest, String.class);
restTemplate = new TestRestTemplate(user.getUsername(), user.getPassword());
base = new URL("http://localhost:" + port + "/mock/mocks");
}
#Test
public void wrongUserAuth_ThenFailed() throws IllegalStateException {
restTemplate = new TestRestTemplate("test", "test");
ResponseEntity<String> response = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
#Test
public void createTwoAccountsForTheSameUser_ThenFailed() throws IllegalStateException {
restTemplate.postForEntity(base.toString(), request, String.class);
ResponseEntity<String> responseTwo = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.CONFLICT, responseTwo.getStatusCode());
assertTrue(responseTwo
.getBody()
.contains("mock"));
}
#Test
public void createAccountDuringWeekend_ThenFailed() throws IllegalStateException {
LocalDate date = LocalDate.of(2000, 1, 1);
PowerMockito.stub(PowerMockito.method(LocalDate.class,"now")).toReturn(date);
ResponseEntity<String> response = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.CONFLICT, response.getStatusCode());
assertTrue(response
.getBody()
.contains("mock"));
}
}

Calling to another eureka client from #configuration class fails

I want to call to hello service (using Netflix Eureka) with (loadBalanced) restTemplate from #Configuration class, but I get an error:
I/O error on POST request for "http://hello/": hello; nested exception is java.net.UnknownHostException: hello
If I do the same call on demand - It works.
My configuration class:
#Configuration
public class OAuth2ResourceServerConfig extends WebSecurityConfigurerAdapter {
#Autowired //It's load balanced in a separate config class
private RestTemplate restTemplate;
#Bean
private String callToHelloService() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map body = new HashMap<String, String>();
body.put("hello", "world");
HttpEntity<Map> entity = new HttpEntity<Map>(body, headers);
HttpStatus status;
try {
status = restTemplate.postForEntity("http://hello/", entity, String.class).getStatusCode();
System.out.print("\nCommunication succeed! status: " + status.value() + "\n");
}
catch (Exception ex) {
System.out.print(ex.getMessage() + "\n");
}
....
....
}
}

UnsatisfiedDependencyException: Error creating bean with name

i'm trying to create db server on Spring, and looked through a lot of similar questions, but no one answer to them can't help me. I can't solve this Error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupController': Unsatisfied dependency expressed through field 'gs'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupServiceImpl': Unsatisfied dependency expressed through field 'gr'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepository': Cannot create inner bean '(inner bean)#1a3c15e0' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1a3c15e0': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
So here's my classes :
GroupController.java
#RestController
public class GroupController {
#Autowired
private GroupService gs;
#RequestMapping(value = "/groups", method = RequestMethod.GET)
#ResponseBody
public List<Group> getAllGroups(){
// return mocklist();
return gs.getAll();
}
private List<Group> mocklist() {
Group g= new Group();
g.setId(1);
g.setGroupName("333");
g.setTutorName("shcefsa");
List<Group> list = new ArrayList<Group>();
list.add(g);
g.setId(2);
g.setGroupName("333");
g.setTutorName("shc321efsa");
list.add(g);
return list;
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.GET)
#ResponseBody
public Group getGroupById(#PathVariable("id") int groupId){
return gs.getById(groupId);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group addGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group updateGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.POST)
#ResponseBody
public void deleteGroup(#PathVariable("id") int groupId){
gs.deleteById(groupId);
}
}
GroupRepository.java
#Repository
public interface GroupRepository extends JpaRepository<Group, Integer> {
}
GroupService.java
#Service
public interface GroupService {
List<Group> getAll();
Group getById(int id);
Group add(Group group);
void deleteById(int id);
}
GroupServiceImpl.java`
#Service
public class GroupServiceImpl implements GroupService {
#Autowired
private GroupRepository gr;
public List<Group> getAll() {
return gr.findAll();
}
public Group getById(int id) {
return gr.findOne(id);
}
public Group add(Group group) {
return gr.save(group);
}
public void deleteById(int id) {
gr.delete(id);
}
Looking at other answers, it seems that everything is fine, but it's obvious that there's an error. Hope you'll help me
UPDATE
Databaseconfig.java
#Configuration
#EnableJpaRepositories("com.homestudio.tutor.server.repository")
#EnableTransactionManagement
#PropertySource("classpath:db.properties")
#ComponentScan("com.homestudio.tutor.server")
public class DatabaseConfig {
#Resource
private Environment env;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(getHibernateProperties());
return em;
}
#Bean
public PlatformTransactionManager platformTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return manager;
}
#Bean
public DataSource dataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setUrl(env.getRequiredProperty("db.url"));
ds.setDriverClassName(env.getRequiredProperty("db.driver"));
ds.setUsername(env.getRequiredProperty("db.username"));
ds.setPassword(env.getRequiredProperty("db.password"));
ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMilles")));
ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMilles")));
ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
return ds;
}
public Properties getHibernateProperties() {
try {
Properties properties = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("hibernate.properties");
properties.load(is);
return properties;
} catch (IOException e) {
throw new IllegalArgumentException("Cannot find file \"hibernate.properties\" in classpath");
}
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan("com.homestudio.tutor.server")
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
converters.add(converter);
}
}

Spring beans are null, #Autowire injections do not work, what went wrong?

I have searched a lot to start with and did not find a solution. This question will be rather long with loads of code, the problem is that at run time DataSource object is null. These are the two ways i am trying to add dataSource beans to the spring container. I guess there is nothing wrong here. And beans are actually created.
package com.stubtech.eztaxi.eztaxiapp.config;
**imports
#Configuration
public class DBConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DBConfig.class);
#Autowired
private Environment environment;
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty("jdbc.driverClass"));
dataSource.setUrl(environment.getProperty("jdbc.url"));
dataSource.setUsername(environment.getProperty("jdbc.username"));
dataSource.setPassword(environment.getProperty("jdbc.password"));
return dataSource;
}
#Bean(name = "jndiDataSource")
public DataSource dataSourceJndi() {
DataSource dataSource = null;
try {
JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
jndiDataSourceLookup.setResourceRef(true);
dataSource = jndiDataSourceLookup.getDataSource("jdbc/EZTaxiDB");
LOGGER.debug("Created DS");
} catch (Exception e) {
LOGGER.error("No DS: " + e.getMessage());
}
return dataSource;
}
}
I have went around using .xml configuration files and used following class for web initialization:
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class);
// Manage lifecycle of the rootContext
container.addListener(new ContextLoaderListener(rootContext));
DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
ServletRegistration.Dynamic registration = container.addServlet("dispatcherServlet", dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy("springSecurityFilterChain");
container.addFilter("springSecurityFilterChain", delegatingFilterProxy).addMappingForUrlPatterns(null, false, "/*");
}
}
At the same time I am trying to use jjwt tokens for autorisation, here is SecurityConfig:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final ITokenAuthService tokenAuthService;
private final UserDetailsService userDetailsService;
private final ISecretReader secretReader;
public SecurityConfig() {
super(true);
this.secretReader = new SecretReaderImpl();
this.userDetailsService = new UserDetailsServiceImpl();
this.tokenAuthService = new TokenAuthServiceImpl();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().and()
.anonymous().and()
.servletApi().and()
.authorizeRequests()
// Allow anonymous resource requests
.antMatchers("/").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("**/*.html").permitAll()
.antMatchers("**/*.css").permitAll()
.antMatchers("**/*.js").permitAll()
// Allow anonymous logins
.antMatchers("/auth/**").permitAll()
// All other request need to be authenticated
.anyRequest().authenticated().and()
// Custom Token based authentication based on the header previously given to the client
.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthService()),
UsernamePasswordAuthenticationFilter.class)
.headers().cacheControl();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public UserDetailsService userDetailsService() {
return userDetailsService;
}
#Bean
public ITokenAuthService tokenAuthService() {
return tokenAuthService;
}
#Bean
public ISecretReader secretReader() {
return secretReader;
}
}
I am trying to authorize using a servlet:
#Component
#WebServlet("/auth/login")
public class AuthenticationServlet extends HttpServlet { // implements ServletResponse {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServlet.class);
private WebApplicationContext springContext;
#Autowired
private UserInfoDAOImpl userInfoDAO;
#Autowired
private AuthenticationManager authenticationManager;
public void init(final ServletConfig config) throws ServletException {
//this.authenticationManager = authenticationManager;
// ApplicationContext context =
// WebApplicationContextUtils.getRequiredWebApplicationContext(
// this.getServletContext());
// authenticationManager = (AuthenticationManager) context.getBean("authenticationManagerBean");
super.init(config);
springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
final AutowireCapableBeanFactory beanFactory = springContext.getAutowireCapableBeanFactory();
beanFactory.autowireBean(this);
LOGGER.debug("Initialised login servlet");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
UserInfo user = userInfoDAO.getUserInfoById("testuser");
String un = request.getParameter("un");
String pw = request.getParameter("pw");
Authentication authrequest = new UsernamePasswordAuthenticationToken(un, pw);
Authentication result = authenticationManager.authenticate(authrequest);
SecurityContextHolder.getContext().setAuthentication(result);
LOGGER.info("Successfully authenticated. Security context contains: " +
SecurityContextHolder.getContext().getAuthentication());
} catch (AuthenticationException e) {
LOGGER.error("Authentication failed: " + e.getMessage());
}
}
}
And finally this is where there is a NullPointer - dataSource is null:
#Component
public class UserInfoDAOImpl implements IUserInfoDAO {
private final static Logger LOGGER = LoggerFactory.getLogger(UserInfoDAOImpl.class);
#Autowired
private DataSource dataSource;
public UserInfo getUserInfoById(String username) {
LOGGER.debug("Get user is called");
String sql = "SELECT u.username name, u.password pass, ur.rolename role FROM " +
"users u INNER JOIN user_role ur on u.id=ur.userid WHERE " +
"u.enabled = 1 and u.username = ?";
UserInfo userInfo = null;
try {
userInfo = new JdbcTemplate(this.dataSource).queryForObject(sql, new Object[]{username},
(rs, rowNum) -> {
UserInfo user = new UserInfo();
user.setUsername(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setRole(rs.getString("role"));
return user;
});
} catch (Exception e) {
LOGGER.error("Failed to fetch user: " + e.getMessage());
}
return userInfo;
}
}
And this is WebConfig:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = ("com.stubtech.eztaxi.eztaxiapp"))
#PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(WebConfig.class);
#Autowired
private ApplicationContext appContext;
public WebConfig(){
LOGGER.debug("_____APP_STARTED_____");
LOGGER.debug("...");
}
}
Log from app initialization:
org.springframework.jdbc.datasource.DataSourceUtils]]
Fetching JDBC Connection from DataSource]]
org.springframework.jdbc.datasource.DriverManagerDataSource]]
org.springframework.jdbc.datasource.DataSourceUtils]]
Returning JDBC Connection to DataSource]]
Failed to fetch user: Property 'dataSource' is required]]
Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#596ded4b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,webConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,DBConfig,securityConfig,userDetailsServiceImpl,userInfoDAOImpl,authenticationServlet,dataSource,jndiDataSource,org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration,authenticationManagerBuilder,enableGlobalAuthenticationAutowiredConfigurer,org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration,delegatingApplicationListener,webSecurityExpressionHandler,springSecurityFilterChain,privilegeEvaluator,autowiredWebSecurityConfigurersIgnoreParents,org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration,objectPostProcessor,org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration,requestDataValueProcessor,authenticationManagerBean,userDetailsService,tokenAuthService,secretReader,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,mvcValidator,mvcUrlPathHelper,mvcViewResolver,mvcPathMatcher,httpRequestHandlerAdapter,requestMappingHandlerMapping,mvcContentNegotiationManager,viewControllerHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,mvcConversionService,beanNameHandlerMapping,mvcResourceUrlProvider,mvcUriComponentsContributor,simpleControllerHandlerAdapter,requestMappingHandlerAdapter,handlerExceptionResolver]; root of factory hierarchy]]
Registering bean definition for #Bean method com.stubtech.eztaxi.eztaxiapp.config.DBConfig.dataSource()]]
Registering bean definition for #Bean method com.stubtech.eztaxi.eztaxiapp.config.DBConfig.jndiDataSource()]]
Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#665a082b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,webConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,DBConfig,securityConfig,userDetailsServiceImpl,userInfoDAOImpl,authenticationServlet,dataSource,jndiDataSource,org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration,authenticationManagerBuilder,enableGlobalAuthenticationAutowiredConfigurer,org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration,delegatingApplicationListener,webSecurityExpressionHandler,springSecurityFilterChain,privilegeEvaluator,autowiredWebSecurityConfigurersIgnoreParents,org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration,objectPostProcessor,org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration,requestDataValueProcessor,authenticationManagerBean,userDetailsService,tokenAuthService,secretReader,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,mvcValidator,mvcUrlPathHelper,mvcViewResolver,mvcPathMatcher,httpRequestHandlerAdapter,requestMappingHandlerMapping,mvcContentNegotiationManager,viewControllerHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,mvcConversionService,beanNameHandlerMapping,mvcResourceUrlProvider,mvcUriComponentsContributor,simpleControllerHandlerAdapter,requestMappingHandlerAdapter,handlerExceptionResolver]; root of factory hierarchy]]
Registered injected element on class [com.stubtech.eztaxi.eztaxiapp.service.impl.UserInfoDAOImpl]: AutowiredFieldElement for private javax.sql.DataSource com.stubtech.eztaxi.eztaxiapp.service.impl.UserInfoDAOImpl.dataSource]]
Processing injected element of bean 'userInfoDAOImpl': AutowiredFieldElement for private javax.sql.DataSource com.stubtech.eztaxi.eztaxiapp.service.impl.UserInfoDAOImpl.dataSource]]
Creating shared instance of singleton bean 'dataSource']]
Creating instance of bean 'dataSource']]
org.springframework.jdbc.datasource.DriverManagerDataSource]]
Eagerly caching bean 'dataSource' to allow for resolving potential circular references]]
Finished creating instance of bean 'dataSource']]
Creating shared instance of singleton bean 'jndiDataSource']]
Creating instance of bean 'jndiDataSource']]
org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup]]
org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup]]
Eagerly caching bean 'jndiDataSource' to allow for resolving potential circular references]]
Not strongly caching class [com.sun.gjc.spi.jdbc40.DataSource40] because it is not cache-safe]]
Finished creating instance of bean 'jndiDataSource']]
Autowiring by type from bean name 'userInfoDAOImpl' to bean named 'dataSource']]
Returning cached instance of singleton bean 'dataSource']]
Returning cached instance of singleton bean 'jndiDataSource']]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]]
Rejected bean name 'dataSource': no URL paths identified]]
Rejected bean name 'jndiDataSource': no URL paths identified]]
org.springframework.jdbc.datasource.DataSourceUtils]]
Fetching JDBC Connection from DataSource]]
org.springframework.jdbc.datasource.DriverManagerDataSource]]
org.springframework.jdbc.datasource.DataSourceUtils]]
Returning JDBC Connection to DataSource]]
Failed to fetch user: Property 'dataSource' is required]]
Clearly you are creating the two different beans of DataSource in your Configuration Class. But at the time of injection you are just doing the following:
#Autowired
private DataSource dataSource;
The problem is that Spring does not know which of the two DataSource Bean is to be injected in here. You have to use #Qualifier to let Spring know which Bean is to be Injected.
Change it to following:
#Autowired
#Qualifier("dataSource")
private DataSource dataSource;
Alternatively, you can replace the two annotations with a single #Resource as follows:
#Resource(name = "dataSource")
private DataSource dataSource;

Resources