Swagger UI doesn't show my APIs when using paths regex - spring-boot

I hava a problem with swagger UI. When I use paths regex in my swagger configuration class, this doesn't find my APIs. When I use the value PathsSelectors.any() this find my APIs but show also my models. I should show only my API so I have decided to use the regex.
This is my Swagger config:
package com.my.project.configurations;
#org.springframework.context.annotation.Configuration
#PropertySource(value = "classpath:application.properties")
#EnableAutoConfiguration
public class Configuration implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
#Bean
public Docket productApi(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(
withClassAnnotation(RestController.class)
.and(RequestHandlerSelectors.basePackage("com.my.project.controller"))
)
.paths(regex("/rest.*"))
.build();
}
this is my Main:
package com.my.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication ( exclude = {SecurityAutoConfiguration.class} )
#EnableJpaRepositories("com.my.project.repository")
#EntityScan(basePackages= {"com.my.project.entities"})
public class MyProjectApplication {
public static void main(String[] args) {
SpringApplication.run(MyProjectApplication.class, args);
}
}
this is my restcontroller:
package com.my.project.controller;
#RestController
#RequestMapping(value = "/rest/pattern")
public class PatternController {
#Autowired
private IPattern patternSvc;
#GetMapping(value = { "/get-all-pattern" }, produces = { MediaType.APPLICATION_JSON_VALUE })
#ApiOperation(value = "get all pattern", tags = "pattern")
public ResponseEntity<BaseAjaxResponse<List<PatternDto>>> findAllPattern(){
HttpStatus status = HttpStatus.OK;
BaseAjaxResponse.BaseAjaxResponseBuilder<List<PatternDto>> builder = BaseAjaxResponse.<List<PatternDto>>builder();
try{
List<PatternDto> listPattern = this.patternSvc.findAllPattern();
if(!listPattern.isEmpty()){
builder
.description("Success")
.size(listPattern.size())
.code(status.value())
.payload(listPattern);
}
else{
builder
.description("Hidden list")
.code(status.value())
.size(0);
}
}catch(Exception e){
status = HttpStatus.INTERNAL_SERVER_ERROR;
builder
.description("No patterns found")
.size(0)
.code(status.value())
.errors(ApiError.builder()
.error(MyProjectInternalError.GENERIC_ERROR.keySet().toArray()[0].toString())
.datails(Collections.singletonList(
ErrorDetail
.builder()
.code(String.valueOf(MyProjectInternalError.GENERIC_ERROR.get("GENERIC ERROR")))
.field("generic")
.message(e.getMessage())
.build()
))
.build());
}
return ResponseEntity.status(status).body(builder.build());
}
}
what am i doing wrong?

I solved adding .ignoredParameterTypes(MyClass1.class, Myclass2.class, ...)
to my Docket bean and setting paths with PathSelectors.any() value

Related

swagger is adding context root twice

I am using swagger 3.0.0-SNAPSHOT with my spring-data-rest. I have context configure in my application property file
server.servlet.context-path=/sample/
my swagger configuration is as follows:
#Configuration
#EnableSwagger2WebMvc
#Import({springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration.class})
public class SwaggerConfig {
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
I am accessing my swagger ui as
http://localhost:8080/sample/swagger-ui.html
all end point in swagger appear like
http://locahost:8080/sample/sample/getHello
http://locahost:8080/sample/sample/getName
http://locahost:8080/sample/sample/getAge
these urls should be
http://locahost:8080/sample/getHello
http://locahost:8080/sample/getName
http://locahost:8080/sample/getAge
How do I avoid swagger to add extra context root to endpoint
My RestController looks like
#RestController
public class HelloController {
#RequestMapping("/hello")
public String getHello(){
return "Hello";
}
#RequestMapping("/name")
public String getName(){
return "Sample Name";
}
#RequestMapping("/age")
public Integer getAge(){
return 37;
}
}
I have confirmed with a sample project that it is happening in every case
When we migrate to swagger 3.0.0-SNAPSHOT, it's include context path also in base path. So, we can remove it by using anonymous implementation of PathProvider. I am able to manage swagger work with the below simple configuration.
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.PathProvider;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
#Configuration
#EnableSwagger2WebMvc
public class SwaggerConfig extends WebMvcConfigurationSupport {
private static final String DESCRIPTION = "My application description";
private static final String TITLE = " My service title";
private static final String API_VERSION = "1.0";
#Value("${server.servlet.context-path}")
private String contextPath;
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title(TITLE).description(DESCRIPTION).version(API_VERSION).build();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).pathProvider(new PathProvider() {
#Override
public String getOperationPath(String operationPath) {
return operationPath.replace(contextPath, StringUtils.EMPTY);
}
#Override
public String getResourceListingPath(String groupName, String apiDeclaration) {
return null;
}
}).select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).build().apiInfo(apiInfo());
}
#Bean
public UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder().displayRequestDuration(true).validatorUrl(StringUtils.EMPTY).build();
}
}

Spring Boot: Add a specific HTTP header in a SOAP request based on Web Service Security (WS-Security, WSS) username

I am exposing a SOAP web service using Spring Boot. This web service is secured using Web Service Security (WSS) which is configured with this security_policy.xml:
<xwss:SecurityConfiguration
xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireUsernameToken
passwordDigestRequired="true" nonceRequired="true" />
</xwss:SecurityConfiguration>
Until this point, the application is working just fine. It is able to authenticate successfully.
Now, I need to add a specific HTTP header based on the WSS username. It is, adds the HTTP header "x-auth-type" with the values:
"test-auth-type" when the username is "test"
"production-auth-type" when the username is "production"
"undefined-auth-type" otherwise
I thought it was easy to add an EndpointInterceptor in which I can set the HTTP header based on the user, but is not been possible to me until now.
My Web Service Configuration class looks like this:
package com.godev.soapwebserviceswithspring;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
private static final String WS_SCHEMA_PATH = "godev_contract.xsd";
private static final String NAMESPACE_URI = "http://godev.com/soap/webservices/demo";
#Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, "/ws/*");
}
#Bean(name = "xml_message")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema billsSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("XmlMessagePort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace(NAMESPACE_URI);
wsdl11Definition.setSchema(billsSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource(WS_SCHEMA_PATH));
}
#Bean
PayloadLoggingInterceptor payloadLoggingInterceptor() {
return new PayloadLoggingInterceptor();
}
#Bean
PayloadValidatingInterceptor payloadValidatingInterceptor() {
final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor();
payloadValidatingInterceptor.setSchema(new ClassPathResource(WS_SCHEMA_PATH));
return payloadValidatingInterceptor;
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("security_policy.xml"));
return securityInterceptor;
}
#Bean
SimplePasswordValidationCallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsersMap(Collections.singletonMap("admin", "pwd123"));
return callbackHandler;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(payloadLoggingInterceptor());
interceptors.add(payloadValidatingInterceptor());
interceptors.add(securityInterceptor());
}
}
My Web Service Endpoint class looks like this:
package com.godev.soapwebserviceswithspring;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.godev.soap.webservices.demo.GetXmlMessageRequest;
import com.godev.soap.webservices.demo.GetXmlMessageResponse;
#Endpoint
public class XmlMessageEndpoint {
private static final String NAMESPACE_URI = "http://godev.com/soap/webservices/demo";
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getXmlMessageRequest")
#ResponsePayload
public GetXmlMessageResponse getXmlDocument(#RequestPayload GetXmlMessageRequest request) {
GetXmlMessageResponse response = new GetXmlMessageResponse();
response.setXmlMessage("<xml>empty document</xml>");
return response;
}
}
Any advice will be very appreciated!
It works for me:
Inject the Security element present in the SOAP header in the Endpoint:
#Endpoint
public class XmlMessageEndpoint {
private static final String NAMESPACE_URI = "http://godev.com/soap/webservices/demo";
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getXmlMessageRequest")
#ResponsePayload
public GetXmlMessageResponse getXmlDocument(#RequestPayload GetXmlMessageRequest request, #SoapHeader("{" + Security.SECURITY_NAMESPACE + "}Security") SoapHeaderElement securityHeader) {
GetXmlMessageResponse response = new GetXmlMessageResponse();
response.setXmlMessage("<xml>empty document</xml>");
return response;
}
In order to parse the securityHeader into something usable, you need to define a couple of POJOs. In my case, I only need the username
POJO for Security element:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(namespace = Security.SECURITY_NAMESPACE, name = "Security")
#Getter
#Setter
public class Security {
public static final String SECURITY_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
#XmlElement(namespace = Security.SECURITY_NAMESPACE, name = "UsernameToken")
private UsernameToken usernameToken;
}
POJO for UsernameToken element:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(namespace = Security.SECURITY_NAMESPACE, name = "UsernameToken")
#Getter
#Setter
public class UsernameToken {
#XmlElement(namespace = Security.SECURITY_NAMESPACE, name = "Username")
private String username;
}
And finally, you can parse the securityHeader using something like this:
public class SoapParser {
public static Security parseSecurityElement(SoapHeaderElement soapHeaderElement) {
Security securityElement = null;
try {
JAXBContext context = JAXBContext.newInstance(Security.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
securityElement = (Security) unmarshaller.unmarshal(soapHeaderElement.getSource());
} catch (JAXBException e) {
e.printStackTrace();
}
return securityElement;
}
}
I hope, it helps!

Spring data with postgress and r2dbc does not work

I am trying to run simple spring boot application with spring data and r2dbc but when i run select query it does return any record.
Configuration
#Configuration
#EnableR2dbcRepositories("com.ns.repository")
public class R2DBCConfiguration extends AbstractR2dbcConfiguration {
#Bean
#Override
public PostgresqlConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration
.builder()
.host("localhost")
.database("employee")
.username("postgres")
.password("nssdw")
.port(5432)
.build());
}
#Bean
public DatabaseClient databaseClient(ConnectionFactory connectionFactory) {
return DatabaseClient.builder().connectionFactory(connectionFactory).build();
}
#Bean
R2dbcRepositoryFactory repositoryFactory(DatabaseClient client) {
RelationalMappingContext context = new RelationalMappingContext();
context.afterPropertiesSet();
return new R2dbcRepositoryFactory(client, context, new DefaultReactiveDataAccessStrategy(new PostgresDialect()));
}
}
Controller which is just simple get request I am not even passing the request paramter just hard coding the id as 1 for the name_id
package com.ns.controller;
import com.ns.entities.Name;
import com.ns.repository.NameRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
#RestController
public class EventDrivenController {
#Autowired
private NameRepository repositoryEvent;
#GetMapping(value = "/pools" )
public Mono<Name> getEmployee() {
Mono<Name> mono = repositoryEvent.findById(1);
repositoryEvent.findById(1).doOnEach(System.out::println);
return mono;
}
}
Reactive repository which is simple get by id request
#Repository
public interface NameRepository extends ReactiveCrudRepository<Name,Integer> {
#Query( "SELECT name_id, last_name, first_name FROM name WHERE name_id = $1")
Mono<Name> findById(Integer id);
}
webclient which is just invoking the get call
public void callwebclient() {
WebClient client = WebClient.create("http://localhost:8080");
Mono<Name> nameMono = client.get()
.uri("/pools")
.retrieve()
.bodyToMono(Name.class);
nameMono.subscribe(System.out::println);
}
main class for spring boot
#SpringBootApplication
public class EventDrivenSystemApplication implements CommandLineRunner {
#Autowired
NameRepository nameRepository;
public static void main(String[] args) {
SpringApplication.run(EventDrivenSystemApplication.class, args);
NameWebClient nameWebClient = new NameWebClient();
nameWebClient.callwebclient();
}
}
Main class which is calling webclient . print statment in the webclient does not print anything
#ComponentScan(basePackages ={"com.ns"})
#SpringBootApplication
#EnableR2dbcRepositories
public class EventDrivenSystemApplication {
public static void main(String[] args) {
SpringApplication.run(EventDrivenSystemApplication.class, args);
NameWebClient nameWebClient = new NameWebClient();
nameWebClient.callwebclient();
}
}

Swagger UI does not show Params

I've got a Spring-Application (2.1.0.RELEASE) and added Swagger and Swagger-UI (2.9.2).
I have a SwaggerConfig class, that I copied from the Baeldung tutorial
Then, there is the App class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#EnableAutoConfiguration
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
And there is the actual REST controller:
#RestController
public class TweetRating {
#GetMapping("/{userid}/tweet")
public static void getTweet(#PathVariable String userid){
System.out.println("UserID: "+ userid);
}
#GetMapping("/")
public static void isWorking(#RequestParam String id){
System.out.println("ID: "+ id);
}
}
The Swagger-UI just won't show the params of the methods. Neither the PathVariable not the RequestParam. Therefore, the "Try it out" function does not make any sense, of course. It looks like this:
Screenshot1
Screenshot2
Why is that and how can I solve it?
Try to apply enableUrlTemplating(true) in you SwaggerConfig :
#Configuration
#EnableSwagger2
public class SwaggerConfig {                                   
    #Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2) 
          .select()                                 
          .apis(RequestHandlerSelectors.any())             
          .paths(PathSelectors.any())  
.enableUrlTemplating(true)                       
          .build();                                          
    }
Also try this one :
#ApiOperation(value = "Dexcription of endpoint")
#RequestMapping
public String doSomething(#ApiParam(value = "Description of path vaiable")#PathVariable("/{code}")

SFTP : BeanPostProcessor interfere with #ServiceActivator and #MessagingGateway

It seems BeanPostProcessor interface implementation is having impact on #ServiceActivator. What should be the way to use BeanPostProcessor with #ServiceActivator. Thanks.
Complete logs are available here logs
Following is Java Config used for SFTP -
package com.ftp.example;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.sftp.outbound.SftpMessageHandler;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.jcraft.jsch.ChannelSftp.LsEntry;
#Configuration
#EnableScheduling
#EnableAspectJAutoProxy
#EnableAsync
#IntegrationComponentScan
#EnableIntegration
#EnableBatchProcessing
#PropertySource("file:C:\\DEV\\workspace_oxygen\\ftp-example\\ftp-example.properties")
public class DependencySpringConfiguration {
private Logger LOG = LoggerFactory.getLogger(DependencySpringConfiguration.class);
#Value("${project.name}")
private String applicationName;
#Value("${${project.name}.ftp.server}")
private String server;
#Value("${${project.name}.ftp.port}")
int port;
#Value("${${project.name}.ftp.username}")
private String username;
#Value("${${project.name}.ftp.password}")
private String password;
#Value("${${project.name}.ftp.remote.directory}")
private String remoteDirectory;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public ProcessStarter processStarter() {
return new ProcessStarter();
}
/* #Bean
public LogInjector logInjector() {
return new LogInjector();
}*/
#Bean
public FTPOutService fTPOutService() {
return new FTPOutService();
}
#Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory sf = new DefaultSftpSessionFactory();
sf.setHost(server);
sf.setPort(port);
sf.setUser(username);
sf.setPassword(password);
sf.setAllowUnknownKeys(true);
return new CachingSessionFactory<LsEntry>(sf);
}
#Bean
#ServiceActivator(inputChannel = "toSftpChannel")
public MessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectory));
handler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
return "fileNameToBeFtp.txt";
}
});
return handler;
}
#MessagingGateway
public interface MyGateway {
#Gateway(requestChannel = "toSftpChannel")
void sendToSftp(File file);
}
}
And We are calling gateway object like this while doing SFTP
Main class
public class FtpExample {
public static String[] ARGS;
private static final Logger LOG = LoggerFactory.getLogger(FtpExample.class);
public static void main(String[] args) throws Exception {
ARGS = args;
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DependencySpringConfiguration.class);
ProcessStarter processStarter = ctx.getBean(ProcessStarter.class);
processStarter.startService();
}
}
Other classes -
public class ProcessStarter {
#Inject
private FTPOutService ftpOutService;
public void startService() {
ftpOutService.ftpToBbg();
}
}
public class FTPOutService {
private static Logger log = LoggerFactory.getLogger(FTPOutService.class);
#Inject
private ApplicationContext appContext;
public void ftpToBbg() {
log.info("Starting FTP out process...");
File file = null;
try {
file = new File("C:\\Temp\\log\\debug\\ftp\\priceindex\\for-upload\\ftp-example.txt.REQ");
MyGateway gateway = appContext.getBean(MyGateway.class);
gateway.sendToSftp(file);
log.info("File {} written successfully on remote server", file);
} catch (Exception e) {
log.error("Error while uploading file {}", file, e);
}
}
}
Above code is working fine unless I am not adding following bean declaration in above defined Java Config -
public LogInjector logInjector() {
return new LogInjector();
}
Above bean definition is having following implementation -
public class LogInjector implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
#Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
#Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(Log.class) != null) {
if (org.slf4j.Logger.class == field.getType()) {
org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(bean.getClass());
field.set(bean, log);
} else if (java.util.logging.Logger.class == field.getType()) {
java.util.logging.Logger log = java.util.logging.Logger.getLogger(bean.getClass().toString());
field.set(bean, log);
}
}
}
});
return bean;
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
#Documented
public #interface Log {
}
Once any BeanPostProcessor implementation is added in Java Config, it creates problem and application not able to see toSftpChannel -
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'toSftpChannel' available at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1199)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at
org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:88)
at
org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:45)
at
org.springframework.integration.gateway.MessagingGatewaySupport.getRequestChannel(MessagingGatewaySupport.java:327)
at
org.springframework.integration.gateway.MessagingGatewaySupport.send(MessagingGatewaySupport.java:368)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:477)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:429)
at
org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:420)
at
org.springframework.integration.gateway.GatewayCompletableFutureProxyFactoryBean.invoke(GatewayCompletableFutureProxyFactoryBean.java:65)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy57.sendToSftp(Unknown Source)
Looks what you have:
#Bean
public LogInjector logInjector() {
return new LogInjector();
}
If you declare BeanPostProcessors as #Bean you have to specify them with the static modifier: https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/core.html#beans-factorybeans-annotations
You may declare #Bean methods as static, allowing for them to be called without creating their containing configuration class as an instance. This makes particular sense when defining post-processor beans, e.g. of type BeanFactoryPostProcessor or BeanPostProcessor, since such beans will get initialized early in the container lifecycle and should avoid triggering other parts of the configuration at that point.

Resources