0

This is my service class:

@Validated
public final class SenderImpl implements Sender {

  private static final Logger LOGGER = LoggerFactory.getLogger(SenderImpl.class);

  private final ExchangeService exchangeService;
  private final IntegratorService integratorService;

  @Autowired
  public SenderImpl(ExchangeService exchangeService, IntegratorService integratorService) {
    this.exchangeService = exchangeService;
    this.integratorService = integratorService;
  }

  @Override
  public String send(@NotNull String rawData, @NotNull String channelName) throws ClientException {
    (...)

    return rawMessage;
  }
}

And here is my IT test for this class where I need to autowire ApplicationContext:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SenderTestIT {

  @Autowired
  private ApplicationContext applicationContext;

  @Autowired
  private Sender sender;

  @MockBean
  private SecurityHelper securityHelper;

  @Before
  public void setup() {
    (...)
  }

  @Test
  public void testSending() throws ClientException {
    // given

    // when
    String response = sender.send("...", "...");

    // then
    assertThat(response).isNotNull();
  }
}

After running following error appears:

Caused by: java.lang.IllegalArgumentException: Cannot subclass final class com.projects.pl.services.SenderImpl
    at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:565)
    at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
    at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.springframework.aop.framework.CglibAopProxy$ClassLoaderAwareUndeclaredThrowableStrategy.generate(CglibAopProxy.java:1004)
    at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
    at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)

It is probably caused by final modifier in my SenderImpl class. Is it good approach? If yes then what is a workaround for this?

Witt
  • 183
  • 1
  • 3
  • 12

1 Answers1

2

Don't make your SenderImpl class final.

Your log trace shows that Spring is using CGLIB.

CGLIB will extend SenderImpl to make a proxy.

And the requirement for CGLIB to work is to have your classes non-final.

Thus the exception

Cannot subclass final class com.projects.pl.services.SenderImpl

You can read more about CGLIB here

MyTwoCents
  • 7,284
  • 3
  • 24
  • 52