有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在运行时动态检索bean?

我试图使用启动期间创建的bean,并在运行时使用它;这两个类都是定型的,但在不同的包中。我一辈子都不能用@Autowired检索redisSession

@ConfigurationProperties(prefix = "redis")
@Configuration
@ConditionalOnProperty(name = "redis.enabled", havingValue = "true")
public class RedisSession {
private static Logger log = LoggerFactory.getLogger(RedisSession.class);
private String hostname;
private int port;
private String password;
private StatefulRedisConnection redisConnection;
private RedisClient redisClient;

@Bean
public RedisAsyncCommands asyncRedisSession() {

    RedisURI redisURI = RedisURI.builder()
            .withHost(hostname)
            .withPort(port)
            .withPassword(password)
            .build();
    redisClient = RedisClient.create(redisURI);
    redisConnection = redisClient.connect();
    return redisConnection.async();
}

(单独包装)

@Component
public class RedisFieldMappers {

    @Autowired
    RedisAsyncCommands redisSession; //redisSession is null
    public HashMap<String, HashMap<String, Object>> getColumnDetails(ArrayList idList,
                                                             String redisSetPrefix, Map<String, String> redisMapper,
                                                             String... fieldNames) throws ExecutionException,
                                                             InterruptedException {
     redisSession.hgetall("foo"); //redisSession is null
     }

共 (0) 个答案