【问题标题】:I am at a loss moving from Spring XML to Java-config我在从 Spring XML 迁移到 Java-config 时不知所措
【发布时间】:2013-03-04 13:07:46
【问题描述】:

我有一个 spring-secuiry.xml 和一个 database.xml 需要移入 Java 配置,但我不知道如何..

这是我的sercuirty.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">


    <global-method-security pre-post-annotations="enabled" />

    <http use-expressions="true">
        <intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/mrequest**" />
        <intercept-url pattern='/*' access='permitAll' />
        <form-login default-target-url="/visit" />

        <logout logout-success-url="/" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="cpilling04@aol.com.dev" password="testing" authorities="ROLE_VERIFIED_MEMBER" />
            </user-service>

        </authentication-provider>
    </authentication-manager>
</beans:beans>

这是我的database.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context 
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                            http://www.springframework.org/schema/jdbc
                            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                            http://www.springframework.org/schema/jee
                            http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <!-- Last changed: $LastChangedDate: 2012-11-19 08:53:13 -0500 (Mon, 19 
        Nov 2012) $ @author $Author: johnathan.smith@uftwf.org $ @version $Revision: 
        829 $ -->

    <context:property-placeholder location="classpath:app.properties" />

    <context:component-scan base-package="org.uftwf" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />

    <jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
        expected-type="javax.sql.DataSource" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.uftwf.inquiry.model.MemberInquiryInformation</value>

            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                <prop key="format_sql">${format_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

谁能告诉我如何更改以下 Java 配置以拥有它们:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.johnathanmsmith.mvc.web"})
public class WebMVCConfig extends WebMvcConfigurerAdapter {

    private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);

    @Bean
    public  ViewResolver resolver() {
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        url.setPrefix("/WEB-INF/view/");
        url.setViewClass(JstlView.class);
        url.setSuffix(".jsp");
        return url;
    }


    @Bean(name = "messageSource")
    public MessageSource configureMessageSource() {
        logger.debug("setting up message source");
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(MESSAGE_SOURCE);
        messageSource.setCacheSeconds(5);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver lr = new SessionLocaleResolver();
        lr.setDefaultLocale(Locale.ENGLISH);
        return lr;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        logger.debug("setting up resource handlers");
        registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        logger.debug("configureDefaultServletHandling");
        configurer.enable();
    }

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }

    @Bean
    public RequestTrackerConfig requestTrackerConfig()
    {
        RequestTrackerConfig tr = new RequestTrackerConfig();
        tr.setPassword("Waiting#$");
        tr.setUrl("https://uftwfrt01-dev.uftmasterad.org/REST/1.0");
        tr.setUser("root");

        return tr;
    }


}

【问题讨论】:

  • 这里有很多代码,但没有很多其他信息。你有什么问题?什么是异常消息?你试过什么?几乎不可能有人能用那堵巨大的代码墙来帮助你。
  • Java Config Support 是 Spring Security 3.2.0 M2 jira.springsource.org/browse/SEC-1953的计划特性@
  • 在当前状态下,Spring 安全配置不能很好地映射到 JavaConfig。您最好的选择可能是将您的安全部分保留在 xml 配置中,并将 xml 导入您的 JavaConfig。正如@Ralph 建议的那样,您可以随时使用下一版本的 Spring Security 将其转换。
  • 好的..如果我同意保密,我怎样才能把数据库的东西放进去......它的

标签: java spring hibernate spring-mvc spring-security


【解决方案1】:

正如 cmets 中所指出的,Java 配置中尚不支持 Spring 安全性。

不久前,我将一个基本的 Spring mvc webapp 转换为完整的(或当时尽可能多的)代码配置。

您可以查看the whole project on github,这一切都应该开箱即用,并且还使用 inializr/bootstrap 的东西来实现 web/html5 的良好实践。

My code config files are all here

正如你在我的安全课上看到的那样,它有点作弊!

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
 * Spring doesn't yet support pure java configuration of spring security
 * so this will just have to import the old fashioned xml file.
 * 
 * @author rob
 *
 */
@Configuration
@ImportResource("classpath:META-INF/spring/security.xml")
public class SecurityConfiguration {}

更新

从 Spring-security 3.2 开始,您已经能够将 Spring-security 转换为基于 Java 的代码配置。我已经把它写在我的博客上:http://automateddeveloper.blogspot.co.uk/2014/02/spring-4-xml-to-annotation-configuration.html

(包括源代码和使用 Spring 4 的完整 spring mvc 项目)

【讨论】:

    【解决方案2】:

    让我们开始吧 - 没有任何 XML 的数据库配置,即基于注释的所有内容。

    我首先创建一个数据库凭据属性文件,并打算将它保存在应用程序的类路径中。我将以 MySQL 和 Hibernate 为例。

    database.properties
    -------------------
    db.driver.class=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://hostname:port/dbname
    db.username=myusername
    db.password=mypassword
    

    现在我将创建一个 Spring 托管类来表示这个配置文件。

    @Component
    @PropertySource(value={"classpath:database.properties"})
    public class DatabaseConfiguration
    {
        @Value("${db.driver.class}")
        private String mDriverClass;
    
        @Value("${db.url}")
        private String mConnectionURL;
    
        @Value("${db.username}")
        private String mUserID;
    
        @Value("${db.password}")
        private String mPassword;
    
        //Getters and setters for the above private variables.
    }
    

    同样,我创建了一个属性文件来定义休眠特定的属性。这些属性也是,我打算保留在类路径中。

    hibernate.properties
    --------------------
    hibernate.dialect= org.hibernate.dialect.MySQLDialect
    hibernate.id.new_generator_mappings=true
    hibernate.show_sql=false
    

    也是定义这个属性文件的spring托管类。

    @Component
    @PropertySource(value={"classpath:hibernate.properties"})
    public class HibernateConfiguration
    {
        @Value("${hibernate.dialect}")
        private String mHibernateDialect;
    
        @Value("${hibernate.id.new_generator_mappings}")
        private boolean mUseNewIdGeneratorMappings;
    
        @Value("${hibernate.show_sql}")
        private boolean mHibernateShowSQL;
    
        //Setters and getters for above fields
    }
    

    使用上面的 HibernateConfiguration 类还有一个小属性类(有用的)。

    @Component
    public class HibernateProperties
    extends Properties
    {
        @Autowired
        public HibernateProperties(HibernateConfiguration config)
        {
            setProperty("hibernate.dialect", config.getDialect());
    
            setProperty("hibernate.id.new_generator_mappings", config.useNewIdGeneratorMappings() ? "true" : "false");
    
            setProperty("hibernate.show_sql", config.showSQL() ? "true" : "false");
        }
    }
    

    现在我将使用 Spring 托管配置类(替换具有数据库相关配置的应用程序上下文 xml 文件的类)。让我将其命名为 DbAppConfig。

    @Configuration
    @EnableTransactionManagement
    public class DbAppConfig
    {
    
        @Autowired
        LocalSessionFactoryBean factory;
    
        @Bean
        @Autowired
        public DataSource getDataSource(DatabaseConfiguration config)
        {
            DriverManagerDataSource datasource = new DriverManagerDataSource();
    
            datasource.setDriverClassName(config.getDriverClass());
    
            datasource.setUrl(config.getConnectionURL());
    
            datasource.setUsername(config.getUserID());
    
            datasource.setPassword(config.getPassword());
    
            return datasource;
        }
    
        @Bean
        @Autowired
        public LocalSessionFactoryBean getSessionFactoryBean(DataSource datasource, HibernateProperties properties)
        {
            LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
    
            factory.setDataSource(datasource);
    
            factory.setHibernateProperties(properties);
    
            factory.setPackagesToScan(new String[]{"my.entity.packages.to.scan"});
    
            return factory;
        }
    
        /**
         * Since the LocalSessionFactoryBean is available on the context, the LocalSessionFactoryBean.getObject will supply
         * the session factory by the auto detection of spring.
         *
         * @param factory
         * @return
         */
        @Bean
        @Autowired
        public HibernateTransactionManager getTransactionManager(SessionFactory factory)
        {
            return new HibernateTransactionManager(factory);
        }
    
        /**
         * inclusion The PropertySourcesPlaceholderConfigurer automatically lets the
         * annotation included property files to be scanned. setting it static to spawn on startup.
         * @return
         */
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() 
        {
            PropertySourcesPlaceholderConfigurer ph = new PropertySourcesPlaceholderConfigurer();
    
            ph.setIgnoreUnresolvablePlaceholders(true);
    
            return ph;
        }
    }
    

    就是这样! 您可以使用 spring 管理的事务管理器。 只需使用 @Transactional 装饰服务(@Service steriotypes)类并在其中使用您的 DAO(@Repository 原型)。

    【讨论】:

    • 你将如何从 Spring MVC 控制器中使用它?
    • 自动装配服务实例并使用它。
    • 我可以在我的 SecurityConfig 类中自动装配 bean 数据源吗?我在这个主题的同一领域有一个问题,我在这里解释过:stackoverflow.com/questions/22749767/…
    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多