Все мои проекты были разработаны с использованием этого руководства: текст
Я использую Sprin Boot: 3.3.2 и MySQL
Это ошибка. я получаю:
ОШИБКА 292047 --- [main] o.s.b.web.embedded.tomcat.Tomcat Starter: Ошибка запуска контекста Tomcat. Исключение: org.springframework.beans.factory.Unsatisfie dDependencyException. Сообщение: Ошибка создания bean-компонента с именем «securityConfig», определенным в URL-адресе [jar:nested:/home/ec2-user/easyrouteprod.jar/!BOOT-INF/classes/!/com/matancita/easyrouteprod/Security Config.class]: Неудовлетворительная зависимость, выраженная через параметр конструктора 0: Ошибка создания компонента с именем «userDetailServiceImpl»: Неудовлетворительная зависимость, выраженная через поле «userRepository»: Ошибка создания компонента с именем «userRepository», определенным в com.matancita.easyrouteprod.dao. UserRepository, определенный в @EnableJpaRepositories, объявленный в EasyrouteprodApplication: невозможно разрешить ссылку на bean-компонент "jpaSharedEM_entityManagerFactory" при установке свойства bean-компонента "entityMana ger"
Это мой интерфейс UserRepository:
@RepositoryRestResource
public interface UserRepository extends CrudRepository {
Optional findByUsername(String username);
}
Это мой класс SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig{
private final UserDetailServiceImpl userDetailsService;
public SecurityConfig(UserDetailServiceImpl userDetailsService){
this.userDetailsService = userDetailsService;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
final AuthenticationManager authenticationManager = authenticationManager(http.getSharedObject(AuthenticationConfiguration.class));
http
.authorizeHttpRequests(authorize ->
authorize.requestMatchers(
"/login",
"/saveUser",
"/editUser/**").permitAll().anyRequest().authenticated())
.sessionManagement(securityContext -> securityContext.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new LoginFilter("/login", authenticationManager), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf(csrf -> csrf.disable())
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// Specify allowed origins explicitly
config.addAllowedOrigin("http://example.com");
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedOrigin("http://192.168.1.3:3000");// You can specify specific origins here
config.addAllowedMethod("*"); // You can specify specific HTTP methods here
config.addAllowedHeader("*"); // You can specify specific headers here
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
Обновление
Я решил проблему с успешным запуском jar в Windows, но теперь я хочу развернуть API в Linux и дает то же самое ошибка. Я обнаружил, что это не работает, потому что при упаковке jar он не создавал папку allTenants.
@Configuration
public class MultitenantConfiguration {
@Value("${defaultTenant}")
private String defaultTenant;
@Bean
@ConfigurationProperties(prefix = "tenants")
public DataSource dataSource() {
//File[] files = Paths.get("classes/allTenants").toFile().listFiles();//for production working on windows when packagin jar but not in linux where i will deploy
File[] files = Paths.get("src/main/resources/allTenants").toFile().listFiles();//working only on ide
Map resolvedDataSources = new HashMap();
for (File propertyFile : files) {
Properties tenantProperties = new Properties();
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
try {
tenantProperties.load(new FileInputStream(propertyFile));
String tenantId = tenantProperties.getProperty("name");
dataSourceBuilder.driverClassName(tenantProperties.getProperty("datasource.driver-class-name"));
dataSourceBuilder.username(tenantProperties.getProperty("datasource.username"));
dataSourceBuilder.password(tenantProperties.getProperty("datasource.password"));
dataSourceBuilder.url(tenantProperties.getProperty("datasource.url"));
resolvedDataSources.put(tenantId, dataSourceBuilder.build());
} catch (IOException exp) {
throw new RuntimeException("Problem in tenant datasource:" + exp);
}
}
AbstractRoutingDataSource dataSource = new MultitenantDataSource();
dataSource.setDefaultTargetDataSource(resolvedDataSources.get(defaultTenant));
dataSource.setTargetDataSources(resolvedDataSources);
dataSource.afterPropertiesSet();
return dataSource;
}
Подробнее здесь: https://stackoverflow.com/questions/788 ... en-i-packa
У меня есть API весенней загрузки, который отлично работает при работе в IDE, но когда я упаковываю API в файл jar и зап ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Jasper Reports выдает исключение при запуске JAR, но работает ОТЛИЧНО в IntelliJ IDE
Anonymous » » в форуме JAVA - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-