1

I have this applicationContext.xml file, which I want to express as a spring @Configuration component. How can I do that? Is there a section in the official spring docs about how to convert XML configurations into Java-based configuration?

Following XML snippet is from this project which implements a custom ViewScope for Spring. In order to use its ViewScope implementation I have to add this configuration in to my applicationContext.xml, But I want to express this configuration in Java.

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="view">
                <bean class="com.github.jneat.jsf.ViewScope"/>
            </entry>
        </map>
    </property>
</bean>
lczapski
  • 4,026
  • 3
  • 16
  • 32
k-var
  • 15
  • 8

2 Answers2

0

You can try this (was in readme of project that you pointed):

import java.util.HashMap;
import java.util.Map;

import com.github.jneat.jsf.ViewScope;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyViewScope {

    @Bean
    public CustomScopeConfigurer customScopeConfigurer() {
        CustomScopeConfigurer configurer = new CustomScopeConfigurer();

        Map<String,Object> scopes = new HashMap<String,Object>();
        scope.put("view", new ViewScope());

        configurer.setScopes(scopes);
        return configurer;
    }
}

You can also see this question

lczapski
  • 4,026
  • 3
  • 16
  • 32
  • This code is confusing to me... how come the `InitViewScope` doesn't have a return type, Is it the constructor (with a typo)? – k-var Oct 29 '19 at 03:23
  • Yes there was a bug (i just copied and pasted it from that repo) . Try current version. – lczapski Oct 29 '19 at 05:56
  • Thanks for 'accepted' if the answer is helpful you can also 'voted up' it @k-var – lczapski Oct 30 '19 at 08:35
0

Try this:

@Bean
public CustomScopeConfigurer customScope(WorkflowScope viewScope) {
    CustomScopeConfigurer configurer = new CustomScopeConfigurer();
    Map<String, Object> viewScope = new HashMap<>();

    viewScopeSet.put("view", viewScope);
    configurer.setScopes(viewScopeSet);

    return configurer;
}
  • As `CustomScopeConfigurer` is a `BeanFactoryPostProcessor` it should be a `public static` method not just a `public` method. This is due the the bean being needed very early in the proces. – M. Deinum Oct 28 '19 at 14:20