spring:使用注解@获取第三方bean实例

发布于:2025-06-12 ⋅ 阅读:(18) ⋅ 点赞:(0)

因为第三方给的bean实例封装在jar包中,无法通过给类添加注解@Component后再获取bean实例,我们可以通过给方法添加注解@Bean,获取bean实例(方法的返回值就是第三方bean实例)。

可获取第三方bean的类

package com.annotation.thirdjar;


import java.util.Date;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


/**
 * @copyright 2003-2025
 * @author    qiao wei
 * @date      2025-04-16
 * @version   1.0
 * @brief     
 * @history   name
 *            date
 *            brief
 */
@Component(value = "factory")
public class DateFactory {
    
    public DateFactory() {
        
    }
    
    @Bean(name = "getDate001")
    public Date getDate() {
        return new Date();
    }
}

配置类,将DateFactory加载。

package com.annotation.config;


import org.springframework.context.annotation.ComponentScan;


/* *
 * @copyright 2003-2025
 * @author    qiao wei
 * @date      2025-06-11
 * @version   1.0
 * @brief     
 * @history   name
 *            date
 *            brief
 */
@ComponentScan(basePackages = "com.annotation")
public class Config {
}

测试类:

package com.annotation.thirdjar;


import java.util.Date;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.annotation.config.Config;


/* *
 * @copyright 2003-2025
 * @author    qiao wei
 * @date      2025-06-11
 * @version   1.0
 * @brief     
 * @history   name
 *            date
 *            brief
 */
class DateFactoryTest {
    
    @Test
    public void test01() {
        ApplicationContext context =
            new AnnotationConfigApplicationContext(Config.class);
        
        Date date = (Date) context.getBean("getDate001");
        System.out.println(date);
    }
}

运行结果:

 方框内为加载包com.annotation中其它类的运行结果,最后一行是获取第三方类Date。

类结构如下图: