【问题标题】:Using Java configuration and constructor injection使用 Java 配置和构造函数注入
【发布时间】:2017-02-16 10:32:32
【问题描述】:

我有一个带有多个参数和@Inject 注释的构造函数的spring bean 类。
有没有办法使用spring Java配置类为该类创建一个bean,而无需实际编写代码来创建对象?像在字段上使用@Bean 之类的吗?

@Bean(MyClassName.class) private MyInterfaceName myBean;

或者也许通过使配置类抽象和bean方法抽象,例如:

@Bean(MyClassName.class) abstract MyInterfaceName myBean();

如果你知道你只有一个类的实现并且你想使用自动连接和构造函数注入,那么每次编写只创建一个新对象的整个方法是很烦人的(而且毫无意义)。

【问题讨论】:

  • 我只是想补充一点,我想使用构造注入,我不喜欢现场自动布线。而且我不想使用类路径扫描来查找bean,我想要一个Java配置类,其中所有bean都被显式创建,我只是不想编写实际创建每个对象的代码。

标签: java spring


【解决方案1】:

你可以使用@Component注解。根据 Spring 文档:

@Component 表示带注释的类是“组件”。这样的类是 使用时被视为自动检测的候选者 基于注释的配置和类路径扫描。

【讨论】:

    【解决方案2】:

    使用@Component 注释。

    表明一个带注释的类是一个“组件”。这样的类是 使用时被视为自动检测的候选者 基于注释的配置和类路径扫描。其他 类级别的注释可以被认为是标识一个组件 同样,通常是一种特殊的组件:例如@Repository 注释或 AspectJ 的 @Aspect 注释。

    Here 是一个例子:

    import org.springframework.stereotype.Component;
    
    @Component
    public class CustomerDAO
    {
        @Override
        public String toString() {
            return "Hello , This is CustomerDAO";
        }
    }
    

    DAO 类:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class CustomerService
    {
        @Autowired
        CustomerDAO customerDAO;
    
        @Override
        public String toString() {
            return "CustomerService [customerDAO=" + customerDAO + "]";
        }
    }
    

    还有一个跑步者课程:

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class App
    {
        public static void main( String[] args )
        {
            ApplicationContext context =
               new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});
    
            CustomerService cust = (CustomerService)context.getBean("customerService");
            System.out.println(cust);
    
        }
    }
    

    你的输出:

    CustomerService [customerDAO=Hello , This is CustomerDAO]
    

    【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 2015-04-22
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2018-03-06
    相关资源
    最近更新 更多