0

我正在构建一个新项目,我想我会尝试一种新的方式来加载我的 Spring 配置。我找到了@Configuration注释并决定尝试一下。

@Configuration
@ImportResource("classpath:myApp-config.xml")
public class MyAppConfig
{
    @Autowired
    private MyClass myClass;

    @Bean(name="someOtherBeanName")
    public MyClass getMyClass ()
    {
        return myClass;
    }

    public void setMyClass( myClass m)
    {
        this.myClass= m;
    }
}

在弹簧配置文件中:

<context:annotation-config/>
<bean name="someOtherBeanName" class="com.MyClass">
    <property name="myClass">
        <map>
            <!-- details not relevant -->
        </map>
    </property>
</bean>

为了利用这一点,我有这样的代码:

//class member
private static MyAppConfig cfg = new MyAppConfig();
...
...
...
//In the class that needs the configuration
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MyAppConfig.class);
ctx.refresh();
//appMgr = cfg.getMyClass();
appMgr = (MyClass) ctx.getBean("someOtherBeanName");

如您所见,我认为我可以从我的配置对象中获取 MyClass 的弹簧配置实例,但我不得不从我的上下文对象中获取它。

我想我误解了方式@Configuration@Bean工作。我离得很近还是很远?

4

4 回答 4

1

您无法从中获取 bean cfg.getMyClass();,存在一些误解。

@Configuration只是弹簧配置的另一种表示,你应该像你的一样理解它application-context.xml,这里没有什么新东西。

于 2013-10-04T21:42:10.927 回答
0

这个

private static MyAppConfig cfg = new MyAppConfig();

不是Spring 托管 bean,因此您将null在调用getMyClass().

另外,以下

@ImportResource("classpath:myApp-config.xml")

@Autowired
private MyClass myClass;

@Bean(name="someOtherBeanName")
public MyClass getMyClass ()
{
    return myClass;
}

是多余的。由于 ,@ImportResource来自 XML 配置的 bean 已经在上下文中。

指示一个或多个包含要导入的 bean 定义的资源。

您不需要@Bean在两者之间使用其他方法。

于 2013-10-04T21:38:33.143 回答
0

您已经很遥远了……以完整的基于 Java 的配置为例:

@Configuration
public class MyAppConfig {

    @Bean
    public MyClass someOtherBeanName() {
        MyClass myClass = new MyClass();
        myClass.setMyProp(null /* details not relevant */);
        return myClass;
    }

}

方法中的其他地方main(这是不变的):

//In the class that needs the configuration
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MyAppConfig.class);
ctx.refresh();
//appMgr = cfg.getMyClass();
appMgr = (MyClass) ctx.getBean("someOtherBeanName");
于 2013-10-04T22:06:20.130 回答
0

添加一些你可能会遇到的东西,如果你仍然找不到 config.xml 或 javaconfig.class。检查您的文件结构。

  • 源代码
    • config.xmljavaconfig.java

将您的配置保存在您的路径中(默认包是 src)

于 2017-04-21T05:35:15.747 回答