Hi booters,
I have a strange behavior with properties overriding in application.yml
during a @SpringBootTest
test.
In application.yml
I defined a:
spring:
task:
execution:
pool:
core-size: 30
max-size: 60
And in application-test.yml
:
spring:
task:
execution:
pool:
core-size: 1
max-size: 1
thread-name-prefix: "test-task"
My test class:
@SpringBootTest
@SpringIntegrationTest
@ActiveProfiles("test")
class TestClass {
....
}
I noticed that all background threads from ThreadPoolTaskExecutor
are prefixed with task-
and there are multiple threads not only one.
I had to define this one:
@TestConfiguration
static class TestConfig implements BeanPostProcessor {
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(1);
taskExecutor.setCorePoolSize(1);
taskExecutor.setThreadNamePrefix("test-task");
return taskExecutor;
}
}
to override the one provided by default.
I noticed that strange behavior when I added this BeanFactoryPostProcessor
bean in my application:
@Bean // note that I depend on ThreadPoolTaskExecutor here
public static BeanFactoryPostProcessor channelsBeanRegistration(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
return (ConfigurableListableBeanFactory beanFactory) -> {
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
CHANNEL_NAMES.forEach(channelName -> {
if (channelName.equals(ERROR_CHANNEL)) {
defaultListableBeanFactory.removeBeanDefinition(ERROR_CHANNEL);
}
BeanDefinition beanDefinition = new RootBeanDefinition(PublishSubscribeChannel.class,
() -> new PublishSubscribeChannel(threadPoolTaskExecutor));
defaultListableBeanFactory.registerBeanDefinition(channelName, beanDefinition);
});
};
}
Am I doing something wrong?
Thanks
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.5.13</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-graphite</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-jmx</artifactId>
<version>1.8.5</version>
</dependency>
Okay, THank you @wilkinsona
Okay, following problem:
I have a more or less stand-alone software which works as a service (more or less a discord bot, but doesn't matter here)
I implemented the JPA stuff in my project.
Long story short.
All works fine.
Table will create in my database
Spring starts - all works fine....
But if I try to save something via saveSurvey.save() I'll get a nullPointerException.
The service is autowired - it works fine
The repository is null - autowired does not work.
Does someone have an Idea why?
Sorry.. Maybe it's a config issue. Have no idea and tried several things i read in several blogs / forums.
Here code snippets:
I added following before my Main
@SpringBootApplication
I added following in my main:
ConfigurableApplicationContext context = SpringApplication.run(Runner.class, args);
I have a separate config class:
@Configuration
@EntityScan(basePackages = {"de.devngs.jeeves.database.mysql.entity"} )
@EnableJpaRepositories(basePackages = {"de.devngs.jeeves.database.mysql.repository"})
public class MySqlConfig {
}
my Service
public interface SurveyService {
List<Survey> findAll();
Optional<Survey> findSurveyById(UUID id);
Survey saveSurvey(Survey survey);
void deleteSurveyById(UUID id);
void deleteSurvey(Survey Survey);
}
my Service impl
@Service
public class SurveyServiceImpl implements SurveyService {
@Autowired
private SurveyRepository surveyRepository;
@Override
public List<Survey> findAll() {
return surveyRepository.findAll();
}
@Override
public Optional<Survey> findSurveyById(UUID id) {
return surveyRepository.findSurveyById(id);
}
@Override
public Survey saveSurvey(Survey survey) {
surveyRepository.save(survey);
return survey;
}
@Override
public void deleteSurveyById(UUID id) {
Optional<Survey> survey = surveyRepository.findSurveyById(id);
survey.ifPresent(value -> surveyRepository.delete(value));
}
@Override
public void deleteSurvey(Survey Survey) {
surveyRepository.delete(Survey);
}
}
My repo
@Repository
public interface SurveyRepository extends JpaRepository<Survey, String> {
Optional<Survey> findSurveyById(UUID id);
}
my entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity(name = "survey")
@Table(name = "survey")
public class Survey {
@Id
@Type(type = "uuid-char")
@Column(name = "id", updatable = false, nullable = false, length = 36)
private UUID id;
private String survey;
private String options;
public Survey(String survey, String options){
this.id = UUID.randomUUID();
this.survey = survey;
this.options = options;
}
}
my Config
spring:
jpa:
properties:
hibernate:
show_sql: false
use_sql_comments: true
open-in-view: true
hibernate:
ddl-auto: "update"
database-platform: "org.hibernate.dialect.MySQL5Dialect"
datasource:
url: "jdbc:mysql://localhost:3306/jeeves"
driver-class-name: "com.mysql.cj.jdbc.Driver"
username: "..."
password: "..."
When setting up multiple datasources I encounter the common
Parameter 0 of method productsEntityManagerFactory in petmenu.config.ProductsDataSourceConfiguration required a bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' that could not be found.
I know it's solved marking one of the DataSource methods as @Primary
, but I cannot understand why.
I'd expect that one to be a solution for conflict of multiple wiring candidate beans, not for the lack of one.
Moreover, considering that the same EntityManagerFactoryBuilder
, that looks like generated somehow from the @Primary
annotated datasource, is used for the rest of the datasources' configuration too, how can this not be a problem?
If the builder is not actually bound to a single DataSource, why it's not provided by SpringBoot as default?
onErrorMap(Exception.class, handleErrorHere)
in a filter, but right after the bodyToMono
call on the client I want to specifically handle a 404 and do something specific for each client instead of global and generic like in the filter so I was curious what order the onError
chain would be called? Specifically wanting to know if I do that catch all in the filter will it happen before my specific 404 one after bodyToMono
Please allow me this noob question. Why doesn't this Spel work if fooBean2 doesn't exist ?
@Bean
public Foo foo( @Value("#{fooBean2 ?: fooBean1}") Foo foo ) {
return new Bar(foo);
}
I'm getting :
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'fooBean2' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?
@Autowired
void configureJpaExceptionTranslator(LocalEntityManagerFactoryBean bean) {
JpaDialect dialect = Objects.requireNonNull(bean.getJpaVendorAdapter()).getJpaDialect();
if (dialect instanceof HibernateJpaDialect) {
SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(bean.getDataSource());
((HibernateJpaDialect) dialect).setJdbcExceptionTranslator(translator);
}
}
@ImportResource("WEB-INF/applicationContext.xml")
the old spring config on my @SpringBootApplication
main class.WEB-INF/applicationContext.xml
is resolved as classpath resource (and therefore not found) instead of beeing resovled as servlet context resource.org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#getResourceByPath
. The call to getServletContext() there returns null, when the resource is resolved. Do you have an idea on how to get this working?
Hi, I am currently trying to make ECDSA related ciphers to work with TLS 1.2 in Spring Cloud Gateway (Spring Boot Parent 2.6.7 and Spring Cloud 2021.0.2). Here's the snippet of WebServerFactoryCustomizer
@Bean
public WebServerFactoryCustomizer<NettyReactiveWebServerFactory> customizer() {
return factory -> factory.addServerCustomizers(httpServer -> httpServer.secure(sslContextSpec -> {
try {
Ssl ssl = factory.getSsl();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
char[] keyStorePassword = ssl.getKeyStorePassword().toCharArray();
keyStore.load(resourceLoader.getResource(ssl.getKeyStore()).getInputStream(), keyStorePassword);
KeyManagerFactory keyManagerFactory = OpenSslCachingX509KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword);
Http11SslContextSpec http11SslContextSpec = Http11SslContextSpec.forServer(keyManagerFactory)
.configure(sslContextBuilder -> {
sslContextBuilder.sslProvider(SslProvider.OPENSSL);
sslContextBuilder.ciphers(Arrays.asList(ssl.getCiphers()));
sslContextBuilder.protocols(ssl.getEnabledProtocols());
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
});
sslContextSpec.sslContext(http11SslContextSpec)
.handlerConfigurator(sslHandler -> {
sslHandler.setCloseNotifyReadTimeout(18000, TimeUnit.MILLISECONDS);
sslHandler.setHandshakeTimeout(19000, TimeUnit.MILLISECONDS);
SSLParameters sslParameters = sslHandler.engine().getSSLParameters();
sslParameters.setUseCipherSuitesOrder(false);
sslHandler.engine().setSSLParameters(sslParameters);
});
} catch (UnrecoverableKeyException | IOException | CertificateException | KeyStoreException |
NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}));
}
But when I try to connect using openssl s_client with ECDHE-ECDSA-AES128-GCM-SHA256 cipher the server returns an error with no shared ciphers, but I do have it in the configuration as
server.ssl.ciphers=TLS_RSA_WITH_AES_128_GCM_SHA256,\
TLS_RSA_WITH_AES_256_GCM_SHA384, \
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
server.ssl.enabled-protocols=TLSv1.2
This behavior was observed when I upgraded versions from Spring Boot 2.3.3.RELEASE and Spring Cloud Hoxton.SR7. Any advice/suggestions would be of great help on fixing or correctly configuring it.
server.tomcat.accept-count
or server.tomcat.max-connections
for netty/webflux?org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.store.bulk.config.DataRoomStoreBulkBeanConfiguration': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.common.config.DataRoomCommonWebConfiguration': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataRoomRequestMappingHandlerAdapter': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.authentication.web.DataRoomSourceAuthenticationWebArgumentResolver': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationProvider': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenService': After spring hibernate upgrade to 5.x getting the exception ....Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenServiceSecureToken': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.authentication.token.securetoken.SecureTokenServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.authentication.securetoken.profile.SecureTokenProfileServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.authentication.securetoken.profile.SecureTokenProfilePersistorImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.trgr.cobalt.dataroom.authentication.securetoken.profile.SecureTokenProfileRepositoryImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'globalSessionFactory' defined in com.trgr.cobalt.dataroom.datasource.config.global.GlobalDataSourceConfiguration: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
@Convertor (javax.persistence) with autoapply true was present in one dependency jar... made it false and @Version started working in web app with hibernate 5.4...
Hello guys, may I ask can we stop executing the rest of the validations after the first validation is failed?
@NotBlank(message ="Username is required") //Stop here if the username is empty.
@Size(min = 6, max = 15, message = "Username must be more than 5 characters and less than 16")
@Pattern.List({
@Pattern(regexp = "^\\S*$", message = "Username cannot contain any whitespaces and special characters"),
@Pattern(regexp = "^[A-Za-z0-9 ]+$", message = "Username cannot contain any whitespaces and special characters")
})
public String username;
public ResponseEntity<String> AddNewUser(@Validated @RequestBody AddUsersEntityDTO addUsersEntityDTO, BindingResult bindingResult) throws Exception{
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
for(ObjectError objectError : list){
System.out.println(objectError.getCode()+" - "+objectError.getDefaultMessage());
}
}
}
Size - Username must be more than 5 characters and less than 16
Pattern - Username cannot contain any whitespaces and special characters
NotBlank - Username is required
Hey,
I have a problem with the date format in Spring Boot 2.6.3, with spring-hateoas (1.4.1).
I have the code:
@Date
@EqualsAndHashCode (callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@ApiModel (description = "Contains information about a license that is either single course license or portfolio lives")
public class LicenseResource extends RepresentationModel <LicenceResource> {
// @JsonFormat (pattern = "yyyy-MM-dd")
private LocalDate startDate;
....
}
and the date format after sending this to the client is array [2011,1,1] instead of "2011-01-01".
Before the upgrade from Spring Boot 2.x.x but without Hateoas (with old Resource support) it worked as expected.
I have tried to use:spring.jackson.date-format = yyyy-MM-dd
andspring.mvc.format.date = yyyy-MM-dd
But none of the above works. I have tried to scan for related GitHub issues but haven't found any recent.
Only using
@JsonFormat (pattern = "yyyy-MM-dd")
on a specific field, but it's a bit too much work.
Or maybe someone has encountered such a problem? How did you setup defaults?