Spring中为bean注入Date对象

本文介绍在Spring框架中如何解决日期类型的属性注入问题,提供了两种解决方案:通过FactoryBean和使用CustomDateEditor进行String到Date的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比如我们有下面的一个bean:

import java.util.Date;
 
public class Customer {
 
	Date date;
 
	public Date getDate() {
		return date;
	}
 
	public void setDate(Date date) {
		this.date = date;
	}
 
	@Override
	public String toString() {
		return "Customer [date=" + date + "]";
	}
 
}

  注意我们上面的bean中有一个Date,但是如果我们使用下面的配置:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="customer" class="com.mkyong.common.Customer">
		<property name="date" value="2010-01-31" />
	</bean>
 
</beans>

  然后我们尝试着运行的话

public class App {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"SpringBeans.xml");
 
		Customer cust = (Customer) context.getBean("customer");
		System.out.println(cust);
 
	}
}

会出现如下的错误:

Caused by: org.springframework.beans.TypeMismatchException: 
	Failed to convert property value of type [java.lang.String] to 
	required type [java.util.Date] for property 'date'; 
 
nested exception is java.lang.IllegalArgumentException: 
	Cannot convert value of type [java.lang.String] to
	required type [java.util.Date] for property 'date': 
	no matching editors or conversion strategy foun
在这里提供两种解决办法:

1. Factory bean

声明一个dateFormat的bean,然后引用。如下解决:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="dateFormat" class="java.text.SimpleDateFormat">
		<constructor-arg value="yyyy-MM-dd" />
	</bean>
 
	<bean id="customer" class="com.mkyong.common.Customer">
		<property name="date">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2010-01-31" />
			</bean>
		</property>
	</bean>
 
</beans>

  

2. CustomDateEditor

我们声明一个CustomDateEditor,将String转换为Date对象。

<bean id="dateEditor"
	   class="org.springframework.beans.propertyeditors.CustomDateEditor">
 
		<constructor-arg>
			<bean class="java.text.SimpleDateFormat">
				<constructor-arg value="yyyy-MM-dd" />
			</bean>
		</constructor-arg>
		<constructor-arg value="true" />
	</bean>

  

 <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dateEditor" />
				</entry>
			</map>
		</property>
	</bean>

  完整的配置为:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="dateEditor"
		class="org.springframework.beans.propertyeditors.CustomDateEditor">
 
		<constructor-arg>
			<bean class="java.text.SimpleDateFormat">
				<constructor-arg value="yyyy-MM-dd" />
			</bean>
		</constructor-arg>
		<constructor-arg value="true" />
 
	</bean>
 
	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dateEditor" />
				</entry>
			</map>
		</property>
	</bean>
 
	<bean id="customer" class="com.mkyong.common.Customer">
		<property name="date" value="2010-02-31" />
	</bean>
 
</beans>

  

 

转载于:https://www.cnblogs.com/rollenholt/archive/2012/12/27/2835191.html

Spring Security中,为某个接口提供永久访问令牌(通常称为JWT或JSON Web Tokens)权限,可以按照以下步骤操作: 1. **添加依赖**:首先,在你的Maven或Gradle项目中引入JWT库,如`jjwt`和`spring-security-jwt`。 ```xml <!-- Maven --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- Gradle --> implementation 'io.jsonwebtoken:jjwt:0.9.1' implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. **配置JWT**: - 创建一个JWTTokenProvider或自定义一个,用于生成和验证JWT。 - 配置SecurityConfig类,启用WebSecurityConfigurerAdapter,并配置JWT过滤器。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { return new JwtAuthenticationTokenFilter(); } // ...其他安全设置 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/your-endpoint").hasRole("ADMIN") // 替换为你的接口路径 .anyRequest().authenticated() .and() .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); } } ``` 3. **创建JWT Token Provider**: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; // ... @Configuration public class JwtConfig { private static final String SECRET_KEY = "your-secret-key"; // 用于加密和解密的密钥 @Value("${jwt.expiration.minutes:30}") private int expirationInMinutes; public String generateToken(User user) { Claims claims = Jwts.claims().setSubject(user.getUsername()) .put("role", user.getRole()) // 根据用户角色添加额外信息 .signWith(SignatureAlgorithm.HS512, SECRET_KEY); return Jwts.builder().setClaims(claims).setExpiration(DateUtils.addMinutes(new Date(), expirationInMinutes)).compact(); } // ...处理验证和刷新token的方法 } ``` 4. **客户端请求**: 客户端每次需要访问受保护的接口时,都需要携带有效的JWT token作为Bearer Header。例如: ```http Authorization: Bearer your-token ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值