zig*_*ggy 5 java configuration spring spring-mvc jakarta-ee
在 Spring MVC Web 应用程序中,我在配置文件中配置了一个 bean:
<bean class="com.callback.CallbackService"/>
Run Code Online (Sandbox Code Playgroud)
在服务类中,bean 被初始化如下:
@Autowired
CallbackService service
Run Code Online (Sandbox Code Playgroud)
上面显示的 CallbackService 通过进行以下三个调用来获取其连接属性(目前无法更改):
System.getProperty("user");
System.getProperty("password");
System.getProperty("connectionURL");
Run Code Online (Sandbox Code Playgroud)
声明 CallbackService 实例的服务类可以通过读取属性文件来访问上述三个值,如下所示:
@Value("${user}")
protected String userName;
@Value("${password}")
protected String password;
@Value("${connection}")
protected String connectionString;
Run Code Online (Sandbox Code Playgroud)
为 CallbackService 设置属性所需的只是设置系统属性(在它们初始化之后),如下所示:
System.setProperty("user", userName);
System.setProperty("password", password);
System.setProperty("connectionURL", connectionString);
Run Code Online (Sandbox Code Playgroud)
然而,我遇到的问题是对象初始化的顺序。属性正在初始化,但看起来 System.setProperty 调用发生在 Spring 从属性文件中准备好它们之前。
我尝试了几种解决方案,但似乎 CallbackService 对象在从属性文件中读取值并调用 System.setProperty 之前实例化。
最终会读取属性文件,因为如果我从 @Controller 方法之一访问它们,我可以看到这些值。问题在于初始化属性和初始化 CallbackService 实例的点。
经过几个小时的谷歌搜索,我尝试了以下解决方案,但似乎没有一个在 CallbackService 实例的初始化/实例化之前填充系统属性
InitiazingBean在afterPropertiesSet()方法中实现和设置系统属性
。ApplicationListener在onApplicationEvent()方法中实现和设置系统属性。lazy-init=trueXML 中 CallbackService bean 定义的设置。上面的第 4 点似乎是我想要的,但是当我将以下内容(带有我需要的三个属性)添加到我的上下文文件时,我没有看到任何区别。
<bean id="systemPrereqs"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" value="#{@systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<!-- The new Properties -->
<util:properties>
<prop key="java.security.auth.login.config">/super/secret/jaas.conf</prop>
</util:properties>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
如何确保在System.setProperty执行调用之前从属性文件中读取值,然后才应实例化 CallbackService 实例?
谢谢
您可以让CallbackService 依赖于初始化系统属性的另一个 bean,例如
class SystemPropertiesInitializer {
SystemPropertiesInitializer(@Value("${user}") String userName,
@Value("${password}") String password,
@Value("${connection}" String connectionString) {
System.setProperty("user", userName);
System.setProperty("password", password);
System.setProperty("connectionURL", connectionString);
}
}
Run Code Online (Sandbox Code Playgroud)
下一个,
<bean id="systemPropertiesInitializer" class="com.callback.SystemPropertiesInitializer"/>
<bean class="com.callback.CallbackService" depends-on="systemPropertiesInitializer"/>
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用@DependsOn注释:
@Component
@DependsOn("systemPropertiesInitializer")
class CallbackService {
// implementation omitted
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25101 次 |
| 最近记录: |