我一直在使用 Spring boot 进行原型设计,在那里我添加了对REST 的依赖,spring-boot-starter-actuator并将spring-boot-starter-data-rest我的测试 REST 端点命名为/info. 应用程序运行时没有任何错误,但是无法调用我的端点并且应用程序一直返回 404。
一段时间后,我发现执行器项目包含 SAME 端点/info并且基本上覆盖了我的自定义 RESTful 端点,因为我没有命名它。
我的问题是:有什么办法可以防止一般的这种行为(意思是 bean 错误地发生冲突)?或者至少在发生这种情况时收到警告消息。
预先感谢您的回答
java spring dependency-injection spring-boot spring-boot-actuator
我有一个带有以下启动代码的 Spring 启动应用程序。Actuator 端点被映射,bean 被移除。我看到执行器端点已注册,然后 bean 被移除。通过SO 线程,这些消息是无害的。但是当我尝试到达任何执行器终点时,我收到错误消息。我不确定我应该进一步研究什么才能使执行器工作。我附上了我提到的所有日志片段。
我用 maven 设置了项目:
Maven Spring Actuator 部分
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Java启动代码
@EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, MessageSourceAutoConfiguration.class })
@EnableConfigurationProperties({ MyAppProperties.class })
@SpringBootApplication
public class MyApp{
private static final Logger LOG = LoggerFactory.getLogger(MyApp.class);
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(MyApp.class);
Environment env = app.run(args).getEnvironment();
LOG.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:{}\n\t" +
"External: \thttp://{}:{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));
}
} …Run Code Online (Sandbox Code Playgroud) public class PlatformEventFactory {
public PlatformEvent createEvent(String eventType) {
if (eventType.equals("deployment_activity")) {
return new UdeployEvent();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个工厂类,它PlatformEvent根据 eventType创建类型对象。
在创建对象private RedisTemplate<String, Object> template后,UdeployEvent 类依赖于我要注入的UdeployEvent对象。
@Component
public class UdeployEvent implements PlatformEvent {
private RedisTemplate<String, Object> template;
private UDeployMessage uDeployMessage;
private static final Logger logger = LoggerFactory.getLogger(UdeployEvent.class);
public UdeployEvent() {
uDeployMessage = new UDeployMessage();
}
/*public void sendNotification() {
}*/
public RedisTemplate<String, Object> getTemplate() {
return template;
}
@Autowired
public void setTemplate(RedisTemplate<String, Object> …Run Code Online (Sandbox Code Playgroud) java spring dependency-injection factory-pattern spring-boot
是否可以在 spring boot 中拥有一个配置文件以及另一个继承大多数父值和 bean 的配置文件?
例如,我有两个配置文件 staging 和 staging-task。我希望 staging-task 继承 staging 配置文件的数据库配置,但是我希望它覆盖 jpa 配置。
配置文件继承是否可用于@Configuration bean。
我正在使用 MySQL 支持的 Spring Boot/JPA。我已经配置了数据库,因此计划使用hibernate.hbm2ddl.auto = validate(因此 Hibernate 不会尝试为我创建数据库,而是使用我提供的数据库并根据我在代码中定义的实体“验证”它)。
我与我的实体有几个多对多关系,例如Book和Author:
// Groovy pseudo code! One book can have multiple authors, and a
// single author can have written many books.
@Entity
class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id
@Column(name="title")
String title
@ManyToMany
List<Author> authors
}
@Entity
class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id
@Column(name="name")
String name
@ManyToMany
List<Book> books
}
Run Code Online (Sandbox Code Playgroud)
在这里,这些类由下表表示:
[books]
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT # PRIMARY KEY
title VARCHAR(50) NOT …Run Code Online (Sandbox Code Playgroud) 我想知道是否有像Flyway这样的工具可以帮助mongodb进行数据库初始化/迁移。我的一些想法是
我正在寻找的是上述两者的混合,一个嵌入式 mongo,它不仅可以与 JUnit 一起使用,还可以从给定的 json 中预填充数据(类似于 Flyway 中的 V1__init.sql)
有没有这样的工具?
我的问题不大。我创建了 MailService 来发送邮件。当我运行程序时,它可以工作。我在resources/application.properties. 我正在使用spring-boot-starter-mail.
@Service
public class MailService {
private JavaMailSender javaMailSender;
@Autowired
public MailService(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void sendMail(String subject, String messageContent, String recipient)
throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setTo(recipient);
messageHelper.setSubject(subject);
messageHelper.setText(messageContent);
javaMailSender.send(mimeMessage);
}
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何为它创建测试。我尝试过这样的事情,我使用的地方org.jvnet.mock-javamail:mock-javamail,但它不起作用:
public class MailServiceTest {
private MailService mailService;
@Mock
private JavaMailSender javaMailSender;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mailService = new MailService(javaMailSender);
Mailbox.clearAll();
}
@Test
public void …Run Code Online (Sandbox Code Playgroud) 我正在为Redis 和 Spring Boot 开发一个小型演示项目。但对于以下GET端点,我收到ClassCastException。-
@GetMapping("/all")
public List<Product> getAllProducts(){
return productRepository.findAll();
}
@GetMapping("/product/{id}")
public Product finProduct(@PathVariable int id){
return productRepository.findProductById(id);
}
Run Code Online (Sandbox Code Playgroud)
服务-
public List<Product> findAll() {
List<Product> products=new ArrayList<>();
redisTemplate.opsForHash().values(HASH_KEY).forEach(e->products.add((Product)e));
return products;
}
public Product findProductById(int id) {
return (Product) redisTemplate.opsForHash().get(HASH_KEY, id);
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误 -
java.lang.ClassCastException: class com.ayushsingh.springdataredisdemo.entity.Product cannot be cast to class com.ayushsingh.springdataredisdemo.entity.Product (com.ayushsingh.springdataredisdemo.entity.Product is in unnamed module of loader 'app'; com.ayushsingh.springdataredisdemo.entity.Product is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @18f69edd)
Run Code Online (Sandbox Code Playgroud)
我引用了以下文章: https: //medium.com/javarevisited/classcast-exception-when-using-redis-and-springboot-frameworks-in-conjunction-ea132dd0d7ea …
java spring classcastexception spring-data-redis spring-boot
我升级到 Spring boot 3.0.7 并尝试让我的 Open API (swagger) 再次工作,具有这些依赖项(根据springdoc):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
...但是当我构建我的应用程序时,出现以下错误:
java.lang.IllegalStateException: Failed to introspect Class [org.springdoc.webmvc.api.OpenApiWebMvcResource] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@1de0aca6]
Run Code Online (Sandbox Code Playgroud)
...“原因”为:
java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
Run Code Online (Sandbox Code Playgroud)
当我查看罐子OpenApiWebMvcResource中的内容时,它确实是从而不是org.springdoc:springdoc-openapi-webmvc-core:1.7.0导入的:javaxjakarta
package org.springdoc.webmvc.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import java.util.Locale;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
...
Run Code Online (Sandbox Code Playgroud)
那么这是一个问题openapi-webmvc-core,还是我接线有问题?
正如我们所说,我尝试将旧项目迁移到最新版本的 Spring Boot(又名 3.1.2)。但是,由于弃用,以下代码段的 .csrf() 和 .requiresChannel() 方法不再起作用。
我找不到替代它们的方法。你能帮我吗?
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig {
private final ApplicationUserService applicationUserService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
public ApplicationSecurityConfig(
ApplicationUserService applicationUserService,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.applicationUserService = applicationUserService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.requiresChannel()
.antMatchers("/actuator/**")
.requiresInsecure()
.and()
.authorizeRequests()
.antMatchers(
"/api/v*/registration/**",
"/register*",
"/login",
"/actuator/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.permitAll()
.defaultSuccessUrl("/",true)
.failureUrl("/login-error")
.and()
.logout()
.logoutUrl("/logout")
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID","Idea-2e8e7cee")
.logoutSuccessUrl("/login");
return http.build();
}
@Bean
public AuthenticationManager authenticationManager( …Run Code Online (Sandbox Code Playgroud) spring-boot ×10
java ×7
spring ×5
email ×1
fongo ×1
hibernate ×1
jpa ×1
junit ×1
many-to-many ×1
mongodb ×1
openapi ×1
spring-mvc ×1
springdoc ×1
unit-testing ×1