简体   繁体   中英

Better way to define a beans in class in spring

In an spring 4 application I creating two beans as below :

    <!-- schemaFactory-->
    <bean id="schemaFact" class="javax.xml.validation.SchemaFactory"
        factory-method="newInstance">
        <constructor-arg value="http://www.w3.org/2001/XMLSchema" />
    </bean>

  <!-- schema -->
    <bean id="schema" class="javax.xml.validation.Schema"
        factory-bean="schemaFact" factory-method="newSchema">
        <constructor-arg value="classpath:/configs/sample.xsd" />
    </bean>

One generates the schema factory and the other uses the factory (to validate xml against xsd).

And in the code:

public class example {

    @Inject
    private Schema aschema;
    ......

   private validate(){
       Validator validator = aschema.newValidator();
       validator.validate(xmlFile); 
 }

}

This works fine, but I wonder if it is possible to write this spring.xml in a way that we don't need to define factory bean separately (and have a simpler spring.xml at the end). As you can see I only need schema bean to be injected in my example class and schemaFact in not needed at all.

Well injected dependencies have to spring beans whether you are using them directly or not.

So even if you are not using SchemaFactory directly in your code but to inject it as dependency in another spring bean, both have to be spring managed beans

You can consider using annotations then you don't need spring file at all.

This is some sample code to create bean in java class. Can create any bean here and autorwired in related class.

This annotations gave us big support to achive it ex- @Configuration

import java.util.Properties;
import javax.persistence.SharedCacheMode;

import........

@Configuration
@ComponentScan(basePackages = {"<package>"})
@EnableTransactionManagement
@PropertySources(value = {@PropertySource(value = {"<property file path>"})})
public class ModulesConfig {

    private static final Logger log = LoggerFactory.getLogger(ModulesConfig.class);

    @Autowired
    private Environment environment;

    @Bean(destroyMethod = "close")
    public BoneCPDataSource getDataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();
        dataSource.setDriverClass(environment.getProperty("database.driver"));
        dataSource.setJdbcUrl(environment.getProperty("database.url"));
        dataSource.setUsername(environment.getProperty("database.username"));
        dataSource.setPassword(environment.getProperty("database.password"));
        dataSource.setIdleConnectionTestPeriodInMinutes(30);
        dataSource.setMaxConnectionsPerPartition(5);
        dataSource.setMinConnectionsPerPartition(2);
        dataSource.setPartitionCount(3);
        dataSource.setAcquireIncrement(2);
        dataSource.setStatementsCacheSize(100);

        return dataSource;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        jpaProperties.setProperty("hibernate.showSql", "false");

        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getDataSource());
        em.setPersistenceUnitName("entityManagerFactory");
        em.setPackagesToScan("<packages>");
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(jpaProperties);
        em.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);

        return em;
    }

    @Bean(name = "transactionManager1")
    @Primary
    public JpaTransactionManager getTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean(name = "transactionManager2")
    public JpaTransactionManager getTransactionManager2() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory2().getObject());

        return transactionManager;
    }

    @Bean
    @Qualifier("VoucherServiceMarshaller")
    public Jaxb2Marshaller getVoucherServiceMarshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath(environment.getProperty("voucher.service.marshaller.contextPath"));

        return marshaller;
    }

    @Bean
    @Qualifier("VoucherServiceTemplate")
    public WebServiceTemplate getVoucherServiceTemplate() {
        WebServiceTemplate template = new WebServiceTemplate(getVoucherServiceMarshaller());
        template.setDefaultUri(environment.getProperty("voucher.service.defaultUri"));

        return template;
    }

    @Bean
    public VoucherServiceProxy getVoucherServiceProxy() {
        VoucherServiceProxy voucherServiceProxy = new VoucherServiceProxy();

        return voucherServiceProxy;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");

        return messageSource;
    }

    @Bean
        public JavaMailSender javaMailSender() {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            Properties mailProperties = new Properties();

            mailProperties.put("mail.smtp.host", environment.getProperty("mail.smtp.host"));
            mailProperties.put("mail.smtp.socketFactory.port", environment.getProperty("mail.smtp.socketFactory.port"));
            mailProperties.put("mail.smtp.socketFactory.class", environment.getProperty("mail.smtp.socketFactory.class"));
            mailProperties.put("mail.smtp.auth", environment.getProperty("mail.smtp.auth"));

            mailSender.setJavaMailProperties(mailProperties);

            mailSender.setUsername(environment.getProperty("mail.username"));
            mailSender.setPassword(environment.getProperty("mail.password"));

            return mailSender;
        }


    @Bean
    public ChargingGatewayServiceProxy getChargingGatewayServiceProxy() {
        ChargingGatewayServiceProxy chargingGatewayServiceProxy = new ChargingGatewayServiceProxy();

        return chargingGatewayServiceProxy;
    }

    @Bean
    @Qualifier("ChargingGatewayServiceMarshaller")
    public Jaxb2Marshaller getChargingGatewayServiceMarshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath(environment.getProperty("cg.service.marshaller.contextPath1"));

        return marshaller;
    }

    @Bean
    @Qualifier("ChargingGatewayServiceTemplate")
    public WebServiceTemplate getChargingGatewayServiceTemplate() {
        WebServiceTemplate template = new WebServiceTemplate(getChargingGatewayServiceMarshaller());
        template.setDefaultUri(environment.getProperty("cg.service.url"));
        template.setMessageSender(getMessageSender());

        return template;
    }

    @Bean
    public HttpComponentsMessageSender getMessageSender() {
        HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
        httpComponentsMessageSender.setConnectionTimeout(Integer.parseInt(environment.getProperty("cg.connection.timeout")));
        httpComponentsMessageSender.setReadTimeout(Integer.parseInt(environment.getProperty("cg.read.timeout")));

        return  httpComponentsMessageSender;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(clientHttpRequestFactory());
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(50000);
        factory.setConnectTimeout(50000);
        return factory;
    }

    @Bean
    public Cache cacheTemp() {
        net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();

        cm.addCache("cacheTemp");
        Cache cache = cm.getCache("cacheTemp");

        return cache;
    }

    @Bean
    public Cache cacheActive() {
        net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();

        cm.addCache("cacheActive");
        Cache cache = cm.getCache("cacheActive");

        return cache;
    }

    @Bean
    public Cache cache() {
        net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();

        cm.addCache("cache");
        Cache cache = cm.getCache("cache");

        return cache;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM