Свойства конфигурации весенней загрузки не могут быть автоматически подключены в Koltin [kotlin.UninitializedPropertyAccessException]

Я хотел бы получить значения параметров по умолчанию, когда пользователь регистрируется из файла свойств.

Для этого я создал класс для управления пользовательскими свойствами

DefaultProperties.kt

@PropertySource("classpath:config/defaults.yml")
@ConfigurationProperties("app.defaults")
class DefaultProperties {

    lateinit var settings: Settings

    class Settings {
        lateinit var keys: Keys
        var language: String = "en-US"
        var timezone: String = "GMT"
        var profilePicture: String = "default"
        var twoFactorAuth: Boolean = false

        class Keys{
            var language: String = "language"
            var timezone: String = "timezone"
            var profilePicture: String = "profile-picture"
            var twoFactorAuth: String = "two-factor-auto"
        }
    }
}

Затем я настраиваю свойства в defaults.yml, например:

app.defaults:
  settings:
    language: "fr-FR"
    two_factor: true

После этого я пытаюсь автоматически связать свойства

SettingsUtil.kt

@Component
class SettingsUtil{

    @Autowired
    lateinit var defaultProperties: DefaultProperties

    fun generateDefaultSettingsMap():MutableMap<String, String>{
        val defaultSettings = defaultProperties.settings
        val defaultKeys = defaultSettings.keys

        val defaultMap = mutableMapOf<String, String>()
        defaultMap[defaultKeys.language] = defaultSettings.language
        defaultMap[defaultKeys.timezone] = defaultSettings.timezone
        defaultMap[defaultKeys.profilePicture] = defaultSettings.profilePicture
        defaultMap[defaultKeys.twoFactorAuth] = defaultSettings.twoFactorAuth.toString()

        return defaultMap
    }

Чтобы наконец позвонить generateDefaultSettingsMap() от лица

User.kt

@Entity
@Immutable
@Cache(region = "userCache", usage = CacheConcurrencyStrategy.READ_ONLY)
data class User(

// Other code

    @ElementCollection
    @CollectionTable(name = "settings", joinColumns= [JoinColumn(name = "user_id", referencedColumnName = "user_id")])
    @MapKeyColumn(name = "key")
    @Column(name="value")
    var settings: MutableMap<String, String> = SettingsUtil().generateDefaultOptionsMap()

Результат, который я получаю при попытке зарегистрировать пользователя -

kotlin.UninitializedPropertyAccessException: lateinit property defaultProperties has not been initialized

Это полная трассировка стека

kotlin.UninitializedPropertyAccessException: lateinit property defaultProperties has not been initialized
    at com.dinarect.dinarectapi.msprofile.util.SettingsUtil.getDefaultProperties(SettingsUtil.kt:18)
    at com.dinarect.dinarectapi.msprofile.util.SettingsUtil.generateDefaultOptionsMap(SettingsUtil.kt:41)
    at com.dinarect.dinarectapi.msprofile.persistence.entity.User.<init>(User.kt:74)
    at com.dinarect.dinarectapi.msprofile.logic.UserServiceImpl.registerUser(UserServiceImpl.kt:69)
    at com.dinarect.dinarectapi.msprofile.controller.UserController.registerUser(UserController.kt:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:154)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:122)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:107)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Есть идеи, что не так?

NB

  1. В среде IDE отображается сообщение "Перезапустите процессор аннотаций конфигурации весенней загрузки для обновления сгенерированных метаданных".

  2. я добавил @component в SettingsUtil так как @Autowired не может быть признан без него.

0 ответов

Другие вопросы по тегам