Injection on Spring Boot

Asked 2 years ago, Updated 2 years ago, 57 views

We are working to make the source you created with Spring Boot work.

If you have a source similar to the one below, Spring will send the application-config.xml to

<beans>
    <bean id="testService" class="test.service.impl.TestServiceAimpl"/>
</beans>

I decided which class to use, but I didn't know how to set it up for Spring Boot.
I would like to determine the class by writing something in application.properties, but what kind of description do you need?
Thank you for your cooperation.

test.controller
  T TestController.java
test.service
  T TestService.java (interface)
test.service.impl
  T TestServiceAimpl.java (TestService Interface Implementation Class A)
  T TestServiceBImpl.java (TestService Interface Implementation Class B)

TestController.java Excerpt

@Autowired
private TestService testService;

TestServiceAimpl.java Excerpt

@Service//@Component is better?
@Profile("TestServiceA")//Added
public class TestServiceAImplementations TestService

TestServiceBImpl.java Excerpt

@Service//@Component is better?
@Profile("TestServiceB")//Added
public class TestServiceBImplifications TestService

application.properties excerpt

spring.profiles.active=TestServiceA//Added

Thank you for your comment, I was able to achieve the behavior I originally expected above.

Also, we considered adding a Configuration class as you commented, but in that case, testServiceA (if spring.profiles.active=A), TestServiceAimpl, and TestServiceBimpl in the Configuration class, the NoUniqueBeanDefinitionException was thrown.

spring

2022-09-30 17:45

1 Answers

@Configuration
public class AppConfig {
  @ Bean TestService testService(){
    return new TestServiceImpl();
  }
}

The class should be under component scanning.The method name will be beanid


2022-09-30 17:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.