标签: spring-java-config

使用Java Config升级到Spring Security 3.2很难删除ROLE_前缀

我在使用Java Config升级到Spring Security 3.2时遇到一些困难,需要自定义RoleVoter删除ROLE_前缀.具体来说,我从原始XML中得到了这个:

<!-- Decision Manager and Role Voter -->
<bean id="accessDecisionManager"
    class="org.springframework.security.access.vote.AffirmativeBased">
    <property name="allowIfAllAbstainDecisions">
        <value>false</value>
    </property>
    <property name="decisionVoters">
        <list>
            <ref local="roleVoter" />
        </list>
    </property>
</bean>

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
    <property name="rolePrefix">
        <value />
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

我试图在我的@Configuration对象中创建类似的配置

@Bean
public RoleVoter roleVoter() {
    RoleVoter roleVoter = new RoleVoter();
    roleVoter.setRolePrefix("");
    return roleVoter;
}

@Bean
public AffirmativeBased accessDecisionManager() {
    AffirmativeBased affirmativeBased = new AffirmativeBased(Arrays.asList((AccessDecisionVoter)roleVoter()));
    affirmativeBased.setAllowIfAllAbstainDecisions(false);
    return affirmativeBased;
}

...

@Override
protected void configure(HttpSecurity http) throws Exception
{ …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-java-config

4
推荐指数
1
解决办法
3638
查看次数

基于Spring Javaconfig的autowire名称无效

我正在尝试使用基于Javaconfig的Spring配置.我有两个相同类型的bean,并尝试通过限定符自动装配它们.但它似乎没有奏效.

这是我的Configuration类



    @Configuration
    @EnableAutoConfiguration
    @ComponentScan("com.test")
    public class BasicConfig {
        @Bean(name = "mysqlSource")
        @Qualifier("mysqlSource")
        public DataSource jdbcTemplateMySql() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8");
            dataSource.setUsername(mysqlUser);
            dataSource.setPassword(mysqlPass);
            return dataSource;
        }

        @Bean(name = "oracleSource")
        @Qualifier("oracleSource")
        public DataSource jdbcSourceOracle() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
            dataSource.setUrl("jdbc:oracle:thin:@lab-scan.tigeritbd.com:1521/evidb.tigeritbd.com");
            dataSource.setUsername(oracleUser);
            dataSource.setPassword(oraclePass);
            return dataSource;
        }
    }


这两个是我正在尝试使用autowire的其他类.

    
    @Repository
    public class TrackingInfiniDBRepo implements DataPutRepo {
        private NamedParameterJdbcTemplate jdbcTemplate;

        @Autowired
        void setJdbcTemplateOracle(@Qualifier("mysqlSource") DataSource dataSource) {
            jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
        }
    }
    

    
    @Repository
    public class OracleDataFetcherRepo implements DataFetcherRepo { …
Run Code Online (Sandbox Code Playgroud)

java spring autowired spring-boot spring-java-config

4
推荐指数
1
解决办法
9130
查看次数

Spring-Boot + Spring-MVC + Thymeleaf + Apache Tiles

我已经有一个带有apache tile和thymeleaf的客户端模块,效果很好。我想将其转换为spring-boot,并希望逐步进行,但是我真的坚持使用它。我不想改变太多,当有人可以告诉我,我应该首先做什么并使其运行时,我会喜欢的。我已经尝试过在javaConfig中编写servlet,但是我也陷入了困境。也许有人可以帮我。如果需要更多信息,请随时询问。

另一个问题是,我需要从xml更改为javaconfig吗?我更喜欢最简单的方法。但是,一旦我将spring-starter依赖项添加到pom中,应用程序就不再起作用。

在此处输入图片说明

=======

POM:

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>at.compax.bbsng</groupId>
    <artifactId>bbsng-client</artifactId>
    <version>0.1.0-SNAPSHOT</version>
</parent>

<artifactId>bbsng-client-mvc</artifactId>
<name>bbsng-client-mvc</name>
<packaging>war</packaging>

<properties>
    <org.apache.tiles-version>2.2.2</org.apache.tiles-version>
    <org.thymeleaf-version>2.0.16</org.thymeleaf-version>
    <slf4j-version>1.7.5</slf4j-version>
    <jackson.version>1.9.10</jackson.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Apache Tiles -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-template</artifactId>
        <version>${org.apache.tiles-version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-servlet</artifactId>
        <version>${org.apache.tiles-version}</version>
    </dependency>

    <!-- ThyMeLeaf ... -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>${org.thymeleaf-version}</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring3</artifactId>
        <version>${org.thymeleaf-version}</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-tiles2</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!-- Jackson JSON Mapper -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version> …
Run Code Online (Sandbox Code Playgroud)

spring-mvc apache-tiles thymeleaf spring-boot spring-java-config

4
推荐指数
1
解决办法
2万
查看次数

Spring JPA Config IllegalArgumentException:没有找到名称的持久性单元

我有一个奇怪的问题,我无法解决这个问题.我用过JPA/Hibernate是Spring之前没有persistence.xml文件,Spring处理了一切.我正在开发一个新项目,这次我决定全部使用Java Config.我的PersistenceConfig.java存在一些问题,它一直说它无法找到持久性单元.如果我注释掉该行,则设置PersistenceUnitName,然后它会抛出IllegalStateException:没有从{classpath*:META-INF/persistence.xml}解析的持久性单元.

我不明白为什么我在使用Java Config时尝试使用persistence.xml而不是在使用XML时.有解决方案吗

这是我的PersistenceConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.testapp.ots.repository"})
public class PersistenceConfig {

    @Autowired
    Environment environment;

    @Bean(name = "datasource")
    public DataSource dataSource() {
        JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        return dsLookup.getDataSource("jdbc/postgres");
    }

    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate jpa spring-java-config

4
推荐指数
1
解决办法
1万
查看次数

无法获得春季批量条件流工作

我无法使用java配置获得条件弹簧批处理流程.我在春季批次样本,春季批次测试代码或堆栈溢出中看到的样本往往显示条件,其中单个步骤需要在条件上执行,或者它是最后一步,或两者.那不是我需要解决的情况.

在程序伪代码中,我希望它表现得像

initStep()
if decision1()
    subflow1()
middleStep()
if decision2()
    subflow2()
lastStep()
Run Code Online (Sandbox Code Playgroud)

因此,subflow1和2是有条件的,但init,middle和last总是执行.这是我的剥离测试用例.在当前配置中,它只是在执行subflow1后退出.

public class FlowJobTest {

private JobBuilderFactory jobBuilderFactory;
private JobRepository jobRepository;
private JobExecution execution;

@BeforeMethod
public void setUp() throws Exception {
    jobRepository = new MapJobRepositoryFactoryBean().getObject();
    jobBuilderFactory = new JobBuilderFactory(jobRepository);
    execution = jobRepository.createJobExecution("flow", new JobParameters());
}

@Test
public void figureOutFlowJobs() throws Exception {

    JobExecutionDecider subflow1Decider = decider(true);
    JobExecutionDecider subflow2Decider = decider(false);

    Flow subflow1 = new FlowBuilder<Flow>("subflow-1").start(echo("subflow-1-Step-1")).next(echo("subflow-1-Step-2")).end();
    Flow subflow2 = new FlowBuilder<Flow>("subflow-2").start(echo("subflow-2-Step-1")).next(echo("subflow-2-Step-2")).end();

    Job job = jobBuilderFactory.get("testJob")
            .start(echo("init"))

            .next(subflow1Decider)
                .on("YES").to(subflow1)
            .from(subflow1Decider)
                .on("*").to(echo("middle")) …
Run Code Online (Sandbox Code Playgroud)

spring-batch spring-java-config

4
推荐指数
1
解决办法
4080
查看次数

Spring Batch Java Config:异常时跳过步骤并转到下一步

例如,我在工作中有 3 个步骤(类似于 Step1):

@Autowired
private StepBuilderFactory stepBuilderFactory;

@Bean
public Step step1() {
    return stepBuilderFactory
            .get("step1")
            .<String, String> chunk(1)
            .reader(reader())
            .processor(processor())
            .writer(writer())
            .build();
}
Run Code Online (Sandbox Code Playgroud)

即使在第 1 步出现异常之后,如何转到第 2 步和第 3 步?我的意思是 Java 中的配置。

java spring spring-batch spring-java-config

4
推荐指数
1
解决办法
1万
查看次数

如何在Spring框架中@Autowired List <Integer>

我有一个配置类如下:

@Configuration
public class ListConfiguration {
    @Bean
    public List<Integer> list() {
        List<Integer> ints = new ArrayList<>();
        ints.add(1);
        ints.add(2);
        ints.add(3);
        return ints;
    }

    @Bean
    public int number() {
        return 4;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也有一个测试类如下

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ListConfiguration.class)
public class ListTest {
    @Autowired
    List<Integer> ints;

    @Test
    public void print() {
        System.out.println(ints.size());
        System.out.println(ints);
    }
}
Run Code Online (Sandbox Code Playgroud)

但输出print方法1[4],为什么不3[1,2,3]?非常感谢您的帮助!

java spring autowired spring-java-config

4
推荐指数
1
解决办法
2126
查看次数

什么是Spring中的JavaConfig?

我只是试着理解注释@Bean的含义和用法,我在本文档中遇到了一个名为JavaConfig 的单词(2.2.1.chapter ).背景如下:

要声明bean,只需使用@Bean批注注释方法即可.当JavaConfig遇到这样的方法时,它将执行该方法并注册(...)

我不明白什么是JavaConfig是Spring ...它究竟起作用了什么?什么时候运行?为什么要跑?

我也看到了这个文档,但没有让我更接近理解它.

java spring spring-mvc spring-java-config

4
推荐指数
2
解决办法
2715
查看次数

BeanDefinitionStoreException异常,因为尝试将应用程序从xml config切换到javaconfig

我尝试从xml配置切换到javaconfig时遇到了一些配置问题.

这是有问题的配置类:

@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@Profile({ "default", "cloud" })
public class DataConfiguration {

    @Value("${database.driverClassName}")
    private String driverClassName;

    @Value("${database.url}")
    private String url;

    @Value("${database.username}")
    private String username;

    @Value("${database.password}")
    private String password;

    @Value("${database.validationQuery}")
    private String validationQuery;

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setTestOnBorrow(Boolean.TRUE);
        dataSource.setTestOnReturn(Boolean.TRUE);
        dataSource.setTestWhileIdle(Boolean.TRUE);
        dataSource.setTimeBetweenEvictionRunsMillis(1800000);
        dataSource.setNumTestsPerEvictionRun(3);
        dataSource.setMinEvictableIdleTimeMillis(1800000);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setMaxActive(5);
        dataSource.setLogAbandoned(Boolean.TRUE);
        dataSource.setRemoveAbandoned(Boolean.TRUE);
        dataSource.setRemoveAbandonedTimeout(10);
        return dataSource;
    }

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

    @Bean
    public …
Run Code Online (Sandbox Code Playgroud)

spring spring-data spring-java-config

3
推荐指数
1
解决办法
3585
查看次数

如何在spring boot应用程序中替换现有的bean?

我是一个Spring引导应用程序,在一个自动配置类中已经创建了一个bean,它来自一个依赖的jar,如bellow:

@Bean
@Order(100)
public StaticRouteLocator staticRouteLocator(AdminServerProperties admin) {
    Collection<ZuulRoute> routes = Collections
            .singleton(new ZuulRoute(admin.getContextPath() + "/api/turbine/stream/**",
                    properties.getUrl().toString()));
    return new StaticRouteLocator(routes, server.getServletPrefix(), zuulProperties);
}
Run Code Online (Sandbox Code Playgroud)

现在我想替换这个bean,但我仍然需要这个有不必要的Bean创建的jar.所以我在我的主要自动配置类中添加了另一个bean创建方法,如下所示:

  @Bean(name="patchedStaticRouteLocator")
  @Order(10)
  @Primary
  @ConditionalOnMissingBean
  public StaticRouteLocator patchedStaticRouteLocator(AdminServerProperties admin) {
    Collection<ZuulProperties.ZuulRoute> routes = Collections
        .singleton(new ZuulProperties.ZuulRoute(admin.getContextPath(),
            properties.getUrl().toString()));
    return new StaticRouteLocator(routes, server.getServletPrefix(), zuulProperties);
  }
Run Code Online (Sandbox Code Playgroud)

但是这无法替换目标bean.错误消息清晰易懂:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.cloud.netflix.zuul.filters.RouteLocator] is defined: more than one 'primary' bean found among candidates: [routeLocator, patchedStaticRouteLocator, staticRouteLocator, compositeRouteLocator, applicationRouteLocator]
Run Code Online (Sandbox Code Playgroud)

我的问题是什么是在春季靴子中更换这种现有豆子的正确方法?提前致谢.

javabeans spring-boot spring-java-config

3
推荐指数
2
解决办法
8519
查看次数