如何将 xml 符号转换为基于注释的符号:Spring - Java

how to convert xml notation to annotation based notation : Spring - Java

我在 spring 上下文 xml 中有以下 xml 配置,我很少使用基于注释的方法,无法弄清楚如何使用注释表示以下内容,需要帮助.

<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
        <constructor-arg>
            <bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
                <property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
                <property name="clientId" value="${clientId}" />
                <property name="clientSecret" value="${clientSecret}" />
                <property name="username" value="${policyAdminUserName}" />
                <property name="password" value="${policyAdminUserPassword}" />
            </bean>
        </constructor-arg>
    </bean>

在我的 java class(策略管理器)中,它被称为以下内容,我实际上是在引用一个示例并尝试将其转换为所有注释基础。

@Autowired
@Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;

编辑: 我尝试为 org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails 创建一个 bean,但不确定如何设置其属性以及如何将其作为构造函数参数访问到 myPolicyAdminTemplate

要设置 bean 的属性,您可以在构造期间使用 @Value

How to inject a value to bean constructor using annotations

还有这个:

Spring: constructor injection of primitive values (properties) with annotation based configuration

或变量中的@Value。您实际上也可以使用@Resource,但我不推荐它。

在你的例子中, org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails

有点像

@Autowired
public ResourceOwnerPasswordResourceDetails(
    @Value("${accessTokenEndpointUrl}") String accessTokenUri,
    @Value("${clientId}") String clientId,
    @Value("${clientSecret}") String clientSecret,
    @Value("${policyAdminUserName}") String username,
    @Value("${policyAdminUserPassword}") String password
)

您可以使用 JavaConfig 配置相同的 bean,如下所示:

@Component
@Configuration
public class AppConfig
{
    @Value("${accessTokenEndpointUrl}") String accessTokenUri;
    @Value("${clientId}") String clientId;
    @Value("${clientSecret}") String clientSecret;
    @Value("${policyAdminUserName}") String username;
    @Value("${policyAdminUserPassword}") String password;

    @Bean
    public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
    {
        return new OAuth2RestTemplate(details);
    }

    @Bean
    public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
    {
         ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
         bean.setAccessTokenUri(accessTokenUri);
         bean.setClientId(clientId);
         bean.setClientSecret(clientSecret);
         bean.setUsername(username);
         bean.setPassword(password);         
         return bean;
    }
}

我将为您提供一个 XML 配置,其中分别包含等效的基于注解的配置,以便您轻松了解如何将 bean 从 xml 更改为 java,反之亦然相反

    <?xml version="1.0" encoding="UTF-8"?>

        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:p="http://www.springframework.org/schema/p"
               xsi:schemaLocation="
                http://www.springframework.org/schema/beans    
                http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.0.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

            <context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
            <mvc:annotation-driven />
            <bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/> 
            <bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>

            <!-- couche de persistance JPA -->
            <bean id="entityManagerFactory"
                  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
                <property name="dataSource" ref="dataSource" />
                <property name="jpaVendorAdapter">
                    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">            
                        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                        <property name="generateDdl" value="true" />
                        <property name="showSql" value="true" />
                    </bean>
                </property>
                <property name="loadTimeWeaver">
                    <bean
                        class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
                </property>
            </bean>

            <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
                <property name="locations" value="classpath:bd.properties"/>
            </bean>

            <!-- la source de donnéees DBCP -->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
                <property name="driverClassName" value="${bd.driver}" />
                <property name="url" value="${bd.url}" />
                <property name="username" value="${bd.username}" />
                <property name="password" value="${bd.password}" />
            </bean>

            <!-- le gestionnaire de transactions -->

            <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory" />
            </bean>


            <!-- traduction des exceptions -->
            <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

            <!-- annotations de persistance -->
            <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


        </beans> 

此文件名为 springrest-sevlet。实际上你可以给你想要的名字后跟“-servlet”并在文件中提到那个名字web.xml

     <web-app> 
             <display-name>Gescable</display-name> 
             <servlet> 
                 <servlet-name>springrest</servlet-name> 
                 <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> 
                 <load-on-startup>1</load-on-startup> 
             </servlet> 
             <servlet-mapping> 
                 <servlet-name>springrest</servlet-name> 
                 <url-pattern>/</url-pattern> 
             </servlet-mapping> 
         </web-app>

这两个文件应该放在文件夹"WEB-INF"中。

现在相当于基于注释的配置

    /*
         * To change this license header, choose License Headers in Project Properties.
         * To change this template file, choose Tools | Templates
         * and open the template in the editor.
         */
        package com.mycompany.backendhibernatejpaannotation.configuration;

        import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
        import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
        import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
        import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
        import javax.sql.DataSource;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
        import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
        import org.springframework.jdbc.datasource.DriverManagerDataSource;
        import org.springframework.orm.jpa.JpaTransactionManager;
        import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
        import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
        import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
        import org.springframework.web.servlet.config.annotation.EnableWebMvc;

        /**
         *
         * @author vivien saa
         */
        @Configuration
        @EnableWebMvc
        @ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
        public class RestConfiguration {

            @Bean
            public IAbonneDao iAbonneDao() {
                return new AbonneDaoImpl();
            }

            @Bean
            public IAbonneService iAbonneService() {
                return new AbonneServiceImpl();
            }

        //    @Bean
        //    public PropertyPlaceholderConfigurer placeholderConfigurer() {
        //        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        //        placeholderConfigurer.setLocations("classpath:bd.properties");
        //        return placeholderConfigurer;
        //    }

            @Bean
            public DataSource dataSource() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
                dataSource.setUsername("root");
                dataSource.setPassword("root");
                return dataSource;
            }

            @Bean
            public HibernateJpaVendorAdapter jpaVendorAdapter() {
                HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
                jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
                jpaVendorAdapter.setGenerateDdl(true);
                jpaVendorAdapter.setShowSql(true);
                return jpaVendorAdapter;
            }

            @Bean
            public InstrumentationLoadTimeWeaver loadTimeWeaver() {
                InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
                return loadTimeWeaver;
            }

            @Bean
            public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
                LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
                entityManagerFactory.setDataSource(dataSource());
                entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
                entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
                return entityManagerFactory;
            }

            @Bean
            public JpaTransactionManager jpaTransactionManager() {
                JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
                jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
                return jpaTransactionManager;
            }

            @Bean
            public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
                return new PersistenceExceptionTranslationPostProcessor();
            }

            @Bean
            public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
                return new PersistenceAnnotationBeanPostProcessor();
            }

        }

此文件必须附有此文件

        package com.mycompany.backendhibernatejpaannotation.configuration;

        import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

        /**
         *
         * @author vivien saa
         */
        public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

            @Override
            protected Class<?>[] getRootConfigClasses() {
                return new Class[]{RestConfiguration.class};
            }

            @Override
            protected Class<?>[] getServletConfigClasses() {
                return null;
            }

            @Override
            protected String[] getServletMappings() {
                return new String[]{"/"};
            }

        }