spring静态属性注入

 

	public static FreeMarkerConfigurer freeMarkerConfigurer; //Freemarker
	
	public FreeMarkerConfigurer getFreeMarkerConfigurer() {
		return StaticResourceBiz.freeMarkerConfigurer;
	}

	@Autowired //@Autowired写到的set方法上,set方法为非静态
	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer) {
		if(StaticResourceBiz.freeMarkerConfigurer == null){
			StaticResourceBiz.freeMarkerConfigurer = freeMarkerConfigurer;
		}
	}

 

freemarker配置,与以上问题没关系

 

<!-- 配置freeMarker的模板路径 -->
<bean id="freemarkerConfig"
	class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
	<property name="freemarkerSettings" ref="freemarkerConfiguration" />
	<property name="templateLoaderPaths">
		<list>
			<value>WEB-INF/templates/</value>
			<value>classpath:/templates/</value>
		</list>
	</property>
	<property name="freemarkerVariables">
		<map>
			<entry key="xml_escape" value-ref="fmXmlEscape" />
			<entry key="extends" value-ref="extendsDirective"></entry>
			<entry key="override" value-ref="overrideDirective"></entry>
			<entry key="block" value-ref="blockDirective"></entry>
			<entry key="super" value-ref="superDirective"></entry>
			<!-- 自定义tag -->
			<entry key="dictTag" value-ref="dictTagDirective"></entry>
		</map>
	</property>
	<property name="preferFileSystemAccess" value="false" />
</bean>

 

### 注入静态属性的方法 在Spring框架中,直接向静态字段注入值并非推荐的做法,因为这违反了依赖注入的原则并可能导致不可预测的行为。然而,在某些特殊情况下确实有需求这样做。 一种常见的方法是使用`@PostConstruct`注解配合自定义逻辑来设置静态变量的值: ```java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class StaticPropertyHolder { private static String myStaticField; @Value("${my.property.value}") private String propertyValue; @PostConstruct public void init() { myStaticField = propertyValue; } public static String getMyStaticField() { return myStaticField; } } ``` 另一种方式是在配置类里通过`static setter`来进行赋值操作: ```java @Configuration public class AppConfig { @Bean public static PropertyConfigurer propertyConfigurer(@Value("${example.static}") final String value) { return new PropertyConfigurer(value); } public static class PropertyConfigurer implements BeanFactoryPostProcessor { private final String value; public PropertyConfigurer(String value){ this.value=value; MyStaticClass.setValue(this.value); // 调用静态setter } ... } } ``` 需要注意的是,上述做法虽然可行,但在实际项目开发过程中应当谨慎考虑是否真的有必要这么做。通常来说,应该尽量避免使用全局状态或共享资源,转而采用更安全的设计模式如单例模式或者工厂模式[^1]。 对于数据访问层面而言,当涉及到数据库交互时,建议利用Spring所提供的抽象层以及自动装配功能,而不是手动管理DataSource实例或其他底层细节[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值