Java equivalent of Spring XML configuration

huangapple go评论84阅读模式
英文:

Java equivalent of Spring XML configuration

问题

我正在尝试找出这段 Spring XML 对应的 Java 代码:

Foo foo = new x.y.Foo();
foo.setName("Rick");

在这里,value 是一个 EncryptablePropertiesFactoryBean。我已经通过 XML 配置使其工作,但是在任何地方似乎都找不到 Java 的替代方法。

英文:

I'm trying to figure out what the Java equivalent to this piece of Spring XML:

<bean id="foo" class="x.y.Foo">
    <property name="name" value="Rick"/>
</bean>

Where value is an EncryptablePropertiesFactoryBean. I have it working with the XML configuration but I can't seem to find a Java alternative anywhere.

答案1

得分: 0

以下是翻译好的部分:

有不同的方法来实现 beans,我建议阅读这份文档以更好地理解 Spring 如何使用 beans:

Spring IoC vs DI

对于答案,一种以编程方式实现的方法可能是:

@Configuration
public class SomeConfiguration {

  @Bean
  public x.y.Foo foo(){
    // 在这里进行一些操作
    EncryptablePropertiesFactoryBean Rick = new EncryptablePropertiesFactoryBean() // 或者任何此类实例
    return new x.y.Foo(Rick); // 其中 x.y.Foo 在其构造函数中具有此类型的属性
  }

}
英文:

There are different ways to implement beans, I would suggest read this documentation for more comprenhention about how Spring uses beans:

Spring IoC vs DI

For the answer, a programatic way to do this could be:

@Configuration
public class SomeConfiguration {

  @Bean
  public x.y.Foo foo(){
    // make something here
     EncryptablePropertiesFactoryBean Rick = new EncryptablePropertiesFactoryBean() // or any other instance of this
     return new x.y.Foo(Rick); //Where x.y.Foo has a property in its constructor of this type
  }

}

答案2

得分: 0

我解决了这个问题限定符是关键部分

@Configuration
public class SomeConfiguration {

    @Bean
    public x.y.Foo foo(@Qualifier("encryptedProperties") Properties properties){
        x.y.Foo foo = new x.y.Foo();
        foo.setPropertiesWithCustomSetter(properties);
        return foo;
    }

    @Bean
    public EncryptablePropertiesFactoryBean encryptedProperties() {
        // 使用所需的加密属性构建EncryptablePropertiesFactoryBean
        return new EncryptablePropertiesFactoryBean ();
    }
}
英文:

I solved this one. The Qualifier is the key part here.

@Configuration
public class SomeConfiguration {

    @Bean
    public x.y.Foo foo(@Qualifier("encryptedProperties") Properties properties){
        x.y.Foo foo = new x.y.Foo();
        foo.setPropertiesWithCustomSetter(properties);
        return foo;
    }

    @Bean
    public EncryptablePropertiesFactoryBean encryptedProperties() {
        // Build EncryptablePropertiesFactoryBean with whatever encrypted properties you need
        return new EncryptablePropertiesFactoryBean ();
    }
}

huangapple
  • 本文由 发表于 2020年10月21日 00:19:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64449284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定