springboot自动装配原理详解
1)传统ssm整合redis的时候 需要在xml的配置文件中 进行大量的配置Bean
我们在这里使用springboot来代替ssm的整合,只是通过xml的形式来整合redis
第一步:加入配置
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
第二步: 配置xml的bean的配置
//配置连接池
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="minIdle" value="10"></property>
<property name="maxTotal" value="20"></property>
</bean>
//配置连接工厂 <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="47.104.128.12"></property> <property name="password" value="123456"></property>
<property name="database" value="0"></property>
<property name="poolConfig" ref="poolConfig"></property>
</bean>
//配置 redisTemplate 模版类
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/>
<!--如果不配置Serializer,那么存储的时候默认使用String,如果用User类型存储,那么会提示错误User can't cast to String! -->
<property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
</bean>
第三步:导入配置
@ImportResource(locations = "classpath:beans.xml") 此注解用于导入xml的配置文件
@SpringBootApplication
@ImportResource(locations = "classpath:beans.xml")
@RestController public class TulingOpenAutoconfigPrincipleApplication {
@Autowired
private RedisTemplate redisTemplate;
public static void main(String[] args) {
SpringApplication.run(TulingOpenAutoconfigPrincipleApplication.class, args);
}
@RequestMapping("/testRedis")
public String testRedis() {
redisTemplate.opsForValue().set("smlz","smlz"); return "OK";
}