Togglz don't pick up Spring-Boot configuration from application.yml - spring-boot

I tried to follow the Togglz guide for Spring Boot, so added all necessary dependencies, created a feature enum:
public enum RetrospectiveBoardFeatures implements Feature {
#Label("Name by cookie")
NAME_BY_COOKIE,
#Label("Name by login")
NAME_BY_LOGIN;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
, configured a EnumBasedFeatureProvider to make that enum known to Spring/Togglz:
#SpringBootApplication
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public FeatureProvider featureProvider() {
return new EnumBasedFeatureProvider(RetrospectiveBoardFeatures.class);
}
}
This all works fine until I wrote a small unit test to see if the feature toggle configuration is applied to my enum (from application.yml):
togglz:
features:
NAME_BY_COOKIE:
enabled: true
NAME_BY_LOGIN:
enabled: false
Test:
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = Application.class)
public class RetrospetiveBoardFeaturesTest {
#Test
public void testCookieFeature() {
assertThat(RetrospetiveBoardFeatures.NAME_BY_COOKIE.isActive(), is(true));
}
}
So my expected result was not met (feature active). Then I added the enabled by default annotation and my feature got active. According to the guide (how I understood it) I don't need to add anything that reads my configuration from Spring and make them known to Togglz. The Togglz samples on GitHub also didn't do anything in this regard (and by looking what Togglz provide in the Spring-Boot starter there is a feature property provider already set up). Maybe I have some wrong versions selected (Spring boot 2.0.1.RELEASE and Togglz 2.5.0.Final)? What did I wrong?

Togglz 2.5.0.Final doesn't support Spring Boot 2 yet. I guess this may be the source of your problem. We are about to release 2.6.0.Final with full Spring Boot 2 support in the next days.
Of course you could give the latest snapshot a try. See all the details here:
https://www.togglz.org/download.html
Also, feel free to join our Gitter chat where we currently discuss all the issue regarding Spring Boot 2 support:
https://gitter.im/togglz/togglz

Related

Application failed to start after spring boot version upgrade from 2.1.18.RELEASE to 2.2.0.RELEASE

When we upgrade the spring-boot-starter-parent version from 2.1.8.RELEASE to 2.2.0.RELEASE, the application is not loading few beans. Due to this, application is failing. #PostConstuct is not able to add BCFIPS Provider in security provider.
#Configuration
#Slf4j
#ComponentScan(basePackages = "com.xxx.yyy.ekms.sdk")
#ConditionalOnProperty(name = "ekms.enabled", havingValue = "true")
public class EKMSClientSdkConfiguration extends ClientConfiguration
{
#PostConstruct
public void addSecurityProvider()
{
Security.addProvider(new BouncyCastleFipsProvider());
}
#Bean
public ApiClientBuilder apiClientBuilder()
{
return new DefaultApiClientBuilder();
}
}
Also, apiClientBuilder bean is not getting created.
The EKMSClientSdkConfiguration is extending ClientConfiguration, which is coming as part of another application jar. This class is not having any annotation.
public abstract class ClientConfiguration {
public ClientConfiguration()
{
}
public abstract void addSecurityProvider();
#Bean
public EKMSClient restClient() {
return new EKMSRestClientImpl(this.apiClient());
}
#Bean
public ApiClient apiClient() {
return Configuration.getDefaultApiClient();
}
}
In our case, EKMSClientSdkConfiguration bean is not getting created and the #PostConstruct is also not getting executed.
I went through the Spring Boot 2.2.RELEASE notes which is pointing to Spring Framework 5.2 upgrade guide. Here, I learned that spring boot 2.2.0 RELEASE is using Spring framework 5.2. In Spring framework 5.2, we have many changes.
It looks like this is the root cause of bean not getting loaded, but I am not sure about it.
Any help will be appreciated. Let me know if additional information is needed.
I found spring.main.lazy-initialization=true property in my application which was causing the above issue. When I removed it from the application.properties, This issue is resolved. This is the major change which was introduced in 2.2.0.RELEASE of spring boot

Does Spring Boot Actuator have a Java API?

We customize the Spring Boot Actuator Info endpoint to include the application version number generated during our Jenkins build. We're using gradle to do this:
if (project.hasProperty('BUILD_NUMBER')) {
version = "${BUILD_NUMBER}"
} else {
version = "0.0.1-SNAPSHOT"
}
That works great for adding the version to the /info endpoint, but I'd like to access it when the application starts and print it to the application log.
I'm hoping the values are exposed in some property value (similar to spring.profiles.active) or through a Java API. That way, I could do something like this:
public class MyApplication{
public static void main(String[] args) throws Exception {
SpringApplication.run(MyApplication.class, args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
System.out.println(environment.getProperty("spring.fancy.path.to.info.version"));
}
}
Looking through the docs, I'm not finding a way to access these values easily in code. Has anyone else had luck with this?
To get exactly the same properties of an actuator endpoint that are exposed through the REST endpoints, you can inject in one of your classes an instance of the respective endpoint class. In your case, the "right" endpoint class would be the InfoEndpoint. There are analogous endpoint classes for metrics, health, etc.
The interface has changed a little between Spring Boot 1.5.x and Spring Boot 2.x. So the exact fully qualified class name or read method name may vary based on the Spring Boot version that you are using. In Boot 1.5.x, you can find most of the endpoints in the org.springframework.boot.actuate.endpoint package.
Roughly, this is how you could build a simple component for reading your version property (assuming that the name of the property inside the info endpoint is simply build.version):
#Component
public class VersionAccessor {
private final InfoEndpoint endpoint;
#Autowired
public VersionAccessor(InfoEndpoint endpoint) {
this.endpoint = endpoint;
}
public String getVersion() {
// Spring Boot 2.x
return String.valueOf(getValueFromMap(endpoint.info()));
// Spring Boot 1.x
return String.valueOf(getValueFromMap(endpoint.invoke()));
}
// the info returned from the endpoint may contain nested maps
// the exact steps for retrieving the right value depends on
// the exact property name(s). Here, we assume that we are
// interested in the build.version property
private Object getValueFromMap(Map<String, Object> info) {
return ((Map<String, Object>) info.get("build")).get("version");
}
}

How to exclude/disable a specific auto-configuration in Spring boot 1.4.0 for #DataJpaTest?

I am using the #DataJpaTest from Spring for my test which will then use H2 as in memory database as described here . I'm also using Flyway for production. However once the test starts FLyway kicks in and reads the SQL file. How can I exclude the FlywayAutoConfiguration and keep the rest as described here in spring documentation in order to let Hibernate create the tables in H2 for me?
#RunWith(SpringRunner.class)
#DataJpaTest
public class MyRepositoryTest {
#Autowired
private TestEntityManager entityManager;
#Autowired
private MyRepository triggerRepository;
}
Have you tried the #OverrideAutoConfiguration annotation?
It says it "can be used to override #EnableAutoConfiguration".
I'm assuming that from there you can somehow exclude FlywayAutoConfiguration
like so:
#EnableAutoConfiguration(exclude=FlywayAutoConfiguration.class)
Adding the dependency on an in-memory database to my build.gradle
e.g. testRuntime "com.h2database:h2:1.4.194"
And adding flyway.enabled=false to application.properties in src/test/resources worked for me.
I am converting an old JDBC app into a spring-data-jpa app and I'm working on the first tests now. I kept seeing a security module instantiation error from spring-boot as it tried to bootstrap the security setup, even though #DataJpaTest should theoretically be excluding it.
My problem with the security module probably stems from the pre-existing implementation which I inherited using PropertySourcesPlaceholderConfigurer (via my PropertySpringConfig import below)
Following the docs here:
http://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#test-auto-configuration
and your comments on #LiviaMorunianu's answer, I managed to work my way past every spring-boot exception and get JUnit to run with an auto-configured embedded DB.
My main/production spring-boot bootstrap class bootstraps everything including the stuff I want to exclude from my tests. So instead of using #DataJpaTest, I copied much of what it is doing, using #Import to bring in the centralized configurations that every test / live setup will use.
I also had issues because of the package structure I use, since initially I was running the test which was based in com.mycompany.repositories and it didn't find the entities in com.mycompany.entities.
Below are the relevant classes.
JUnit Test
#RunWith(SpringRunner.class)
#Transactional
#Import({TestConfiguration.class, LiveConfiguration.class})
public class ForecastRepositoryTests {
#Autowired
ForecastRepository repository;
Forecast forecast;
#Before
public void setUp() {
forecast = createDummyForecast(TEST_NAME, 12345L);
}
#Test
public void testFindSavedForecastById() {
forecast = repository.save(forecast);
assertThat(repository.findOne(forecast.getId()), is(forecast));
}
Live Configuration
#Configuration
#EnableJpaRepositories(basePackages = {"com.mycompany.repository"})
#EntityScan(basePackages = {"com.mycompany.entity"})
#Import({PropertySpringConfig.class})
public class LiveConfiguration {}
Test Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
CacheAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class,
TestDatabaseAutoConfiguration.class,
TestEntityManagerAutoConfiguration.class })
public class TestConfiguration {
// lots of bean definitions...
}
PropertySpringConfig
#Configuration
public class PropertySpringConfig {
#Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
throws IOException {
return new CorePropertySourcesPlaceholderConfigurer(
System.getProperties());
}
}
In my particular case, i needed to disable the FlywayDB on in-memory integration tests. These are using a set of spring annotations for auto-configuring a limited applicationContext.
#ImportAutoConfiguration(value = TestConfig.class, exclude = FlywayAutoConfiguration.class)
the exclude could effectively further limit the set of beans initiated for this test
I had the same problem with my DbUnit tests defined in Spock test classes. In my case I was able to disable the Flyway migration and managed to initialize the H2 test database tables like this:
#SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE,
properties = ["flyway.enabled=false", "spring.datasource.schema=db/migration/h2/V1__init.sql"])
I added this annotation to my Spock test specification class. Also, I was only able to make it work if I also added the context configuration annotation:
#ContextConfiguration(classes = MyApplication.class)
I resolved the same issue by excluding the autoconfiguration from my application definition, i.e.
#SpringBootApplication(exclude = {FlywayAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
you can also sue the following annotation:
#RunWith(SpringRunner.class)
#DataJpaTest(excludeAutoConfiguration = {MySqlConfiguration.class, ...})
public class TheClassYouAreUnitTesting {
}
You can just disable it in your test yaml file:
flyway.enabled: false

Sonar complains about Spring Boot configuration

I have this class to start up the spring-cloud config server. It is a spring-boot application.
#SpringBootApplication
#EnableConfigServer
#EnableDiscoveryClient
public class ConfigServerApplication {
public static void main( String[] args ) {
SpringApplication.run( ConfigServerApplication.class, args );
}
}
The application runs fine and all my unit tests are fine. However, in our bamboo pipeline, it will initial a sonar process to analyze the code. We keep getting these minor warnings indicating the following:
Utility classes should not have a public constructor
I know that this is a minor issue, but I have been tasked with removing these from our code.
Ideally, you would mark the class final and provide a private constructor, or so all searches provide as a solution. However, a Spring Configuration class cannot be made final and cannot have a private constructor.
Any ideas how to resolve this?
I'm afraid this isn't a problem spring-boot or spring-cloud can solve. You need to add exceptions to your sonar configuration.
Adjusting your sonar settings would be a nicer approach of course, but if you want to please the machine spirits, you can simply add a non-static dummy function to your class, making it "non-utility" in the eyes of the Sonar checker.
It's easy to test:
#RunWith(SpringRunner.class)
#SpringBootTest
public class YourApplicationTest {
#Test
public void shouldLoadApplicationContext() {
}
#Test
public void applicationTest() {
YourApplication.main(new String[] {});
}
}
Now Sonar is saying, this is tested!
(Kudos goes out to: Robert # https://stackoverflow.com/a/41775613/863403)

Hibernate Envers with Spring Boot - configuration

I'm trying to setup Hibernate Envers to work with my Spring Boot application.
I've included the Envers dependency and added #Audited annotations and it works fine, but I'm unable to configure specific Envers properties, Spring Boot doesn't seem to pick them up.
Specifically, I've tried to set the different db schema for audit tables by putting these to application.properties, but without luck:
hibernate.envers.default_schema=app_audit
or
org.hibernate.envers.default_schema=app_audit
or
spring.jpa.hibernate.envers.default_schema=app_audit
Neither of these work. Does anyone know how to set these?
EDIT.
As M. Deinum suggested I tried:
spring.jpa.properties.org.hibernate.envers.default_schema=app_audit
and it worked!
For all those configuration settings that aren't by default available you can specify them by simply prefixing them with spring.jpa.properties. Those properties will be added, as is, to the EntityManagerFactory (as JPA Properties).
spring.jpa.properties.org.hibernate.envers.default_schema=app_audit
Adding the above to the application.properties will add the properties and should configure Hibernate Envers.
This is also documented in the Spring Boot reference guide.
Links
Configure JPA properties
Envers Properties
Looking through the HibernateJpaAutoConfiguration class I can't see any support for envers properties. The following might not be the best solution but nevertheless your can give it a try.
In order to have Spring Boot support the envers properties you have to:
override the current AutoConfiguration class that Spring Boot uses to configure the Hibernate properties, so it will read the envers properties from your property files.
This will read the spring.jpa.hibernate.envers.default_schema from your file and add it to the properties of the entityManagerFactoryBean:
#Configuration
public class HibernateEnversAutoConfiguration extends HibernateJpaAutoConfiguration {
private RelaxedPropertyResolver environment;
public HibernateEnversAutoConfiguration() {
this.environment = null;
}
#Override
public void setEnvironment(Environment environment) {
super.setEnvironment(environment);
this.environment = new RelaxedPropertyResolver(environment, "spring.jpa.hibernate.");
}
#Override
protected void configure(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
super.configure(entityManagerFactoryBean);
Map<String, Object> properties = entityManagerFactoryBean.getJpaPropertyMap();
properties.put("hibernate.envers.default_schema", this.environment.getProperty("envers.default_schema"));
}
}
exclude the original HibernateJpaAutoConfiguration that Spring Boot uses and add your own as a bean so it will be replaced:
#EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class)
#EnableJpaRepositories(basePackages = "com.gabrielruiu.test")
#EntityScan(basePackages = "com.gabrielruiu.test")
#ComponentScan(basePackages = "com.gabrielruiu.test")
#Configuration
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
#Bean
public HibernateEnversAutoConfiguration hibernateEnversAutoConfiguration() {
return new HibernateEnversAutoConfiguration();
}
}
For those using MySQL and Spring Boot, the suggestion of using:
spring.jpa.properties.org.hibernate.envers.default_schema=yourAuditSchema will not work.
Use this instead:
spring.jpa.properties.org.hibernate.envers.default_catalog=yourAuditSchema
I use with yaml format:
spring:
jpa:
properties:
org:
hibernate:
format_sql: false
envers:
audit_table_suffix: AUDIT
revision_field_name: NRO_ID_REVISAO_AUDITORIA
revision_type_field_name: TPO_REVISAO_AUDITORIA

Resources