Home > database >  Spring disable component call
Spring disable component call

Time:10-11

I am having a class let's say it's name is "MyHandler.java", which is a maven dependence, also the file is read only, i can't modify it. The purpose of MyHandler is that he logs information when performing actions. For example my app has a keyboard for input, where if i am pressing some keys on the app keyboard it triggers method from MyHandler.java which displays in logs what key has been triggered, for example "BUTTON 1", or "BUTTON 2". Now i implemented a login functionality into my app, everything works, but when i look into logs you can easily see the password and login, which is not good. So, i tried to create a component to override the functionality ->

@Primary
@Component
public class OverrideTry extends MyHandler {
 
 @Override
 public void onButtonClickAction() {
   System.out.println("trying to display this one");
 } 

I thought this would work, but when i am trying to use it i am getting in my console the message "trying to display this one" the previous from the MyHandler, which i do not want to have.

@Component
public class MyHandler 
   implements onButtonClickAction {
@Override
 public void onButtonClickAction (OnButtonClickAction context) {
   log(btn, "btn_id: '%s' body: '%s'", context.getId(), context.getText()); // so when i press 1 in console i get btn_id 1 1, which is information i would not like to get.
 }

}

So, my answer is what should i do to cancel MyHandler's calling inside methods? I've tried using extends and annotating with primary but as i see it does not work. How can i achieve this? I can't delete MyHandler, also it's read only, i can't modify.

CodePudding user response:

Classes annotated as @Compoment are scanned by Spring because it is configured to do so. Somewhere you must have it configured like this:

@Configuration
@EnableAutoConfiguration
@ComponentScan

One can adjust the packages to scan excluding the package with the original MyHandler implementation.

Baeldung article Spring Component Scanning makes following suggestion:

@ComponentScan(excludeFilters = 
   @ComponentScan.Filter(type=FilterType.REGEX,
   pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*"))

If you have an old XML based Spring project, Spring documentation shows how to do it using XML configuration:

<beans>
    <context:component-scan base-package="org.example">
        <context:include-filter type="regex" expression=".*Stub.*Repository"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>
</beans>
  • Related