根据bean的名称获取bean,静态方法查询数据库
根据bean名称获取bean
1.先创建bean,如template
package com.test.game.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;@Configuration
public class TemplateConfig {@Beanpublic JdbcTemplate mysqlTemplate(DataSource dataSource){return new JdbcTemplate(dataSource);}
}
2.创建获取bean的工具
package com.test.game.utils;import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class SpringContextUtil implements ApplicationContextAware {private static ApplicationContext context = null;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {context = applicationContext;}/*** 获取当前环境* @return*/public static String getActiveProfile(){return context.getEnvironment().getActiveProfiles()[0];}/*** 根据bean名称获取bean* @param name* @return*/public static Object getBean(String name){return context.getBean(name);}/*** 通过class获取bean* @param clazz* @return* @param <T>*/public static <T> T getBean(Class<T> clazz){return context.getBean(clazz);}/*** 根据bean名和class获取bean* @param name* @param clazz* @return* @param <T>*/public static <T> T getBean(String name,Class<T> clazz){return context.getBean(name,clazz);}}
3.使用工具获取bean
package com.test.game.utils;import com.test.game.entity.PlayGift;
import com.test.game.enums.CostType;
import com.test.game.enums.DrawType;
import com.test.game.enums.GiftState;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;public class CommonDrawUtils {public static List<PlayGift> getGifts(int num,String drawType){JdbcTemplate mysqlTemplate = (JdbcTemplate)SpringContextUtil.getBean("mysqlTemplate");String sql = "select * from play_gift where state = ? and box_draw = ? and pet_draw = ? and type = ? and draw_type = ?";String costType = CostType.DRAMOND.name();if (DrawType.AMETHYST.name().equals(drawType) || DrawType.GOLD.name().equals(drawType)){costType = CostType.AMETHYST.name();}List<PlayGift> playGifts = mysqlTemplate.query(sql, new Object[]{GiftState.UP.getCode(), true, true, costType, drawType},new RowMapper<PlayGift>() {@Overridepublic PlayGift mapRow(ResultSet resultSet, int i) throws SQLException {PlayGift playGift = new PlayGift();playGift.setState(resultSet.getBoolean("state"));playGift.setBoxDraw(resultSet.getBoolean("box_draw"));playGift.setPetDraw(resultSet.getBoolean("pet_draw"));playGift.setType(resultSet.getString("type"));playGift.setDrawType(resultSet.getString("draw_type"));return playGift;}});return playGifts;}
}