标签: spring-java-config

弹簧测试@async方法

我正在尝试测试@AsyncSpring的注释是否在我的项目中按预期工作.但事实并非如此.

我有这个测试:

 @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = GlobalConfiguration.class)
    public class ActivityMessageListenerTest {

    @Autowired
    private ActivityMessageListener activityMessageListener;

    private Long USER_ID = 1l;
    private Long COMPANY_ID = 2l;
    private Date DATE = new Date(10000000);
    private String CLASSNAME = "className";
    private Long CLASSPK = 14l;
    private Integer TYPE = 22;
    private String EXTRA_DATA = "extra";
    private Long RECIVED_USER_ID = 99l;

    @Before
    public void setup() throws Exception {
    }

    @Test
    public void testDoReceiveWithException() throws Exception {
        System.out.println("Current thread " +      Thread.currentThread().getName());
        Map<String, Object> values …
Run Code Online (Sandbox Code Playgroud)

spring spring-aop spring-java-config spring-aspects

7
推荐指数
1
解决办法
3692
查看次数

如何使用spring java config将X-Frame-Options响应头设置为允许来自值?

如何使用spring java config设置值为allow-from的X-Frame-Options响应头?

http.headers().disable()
    .addHeaderWriter(new XFrameOptionsHeaderWriter(
      new WhiteListedAllowFromStrategy(
        Arrays.asList("https://example1.com", "https://example2.com"))));
Run Code Online (Sandbox Code Playgroud)

在Http Response标题中,我得到:

X-Frame-Options:"ALLOW-FROM DENY".

为什么我的起源不在标题值中列出?

spring-security http-headers x-frame-options spring-java-config

7
推荐指数
2
解决办法
9812
查看次数

@ImportAutoConfiguration和@Import有什么区别

是否真的org.springframework.boot.autoconfigure.ImportAutoConfiguration是改进替换org.springframework.context.annotation.Import因为同样和另外尊重

@AutoConfigureBefore,@AutoConfigureAfter@AutoConfigureOrder

spring-boot spring-java-config

7
推荐指数
1
解决办法
3614
查看次数

Spring Security 3.2:@Autowire不能在Spring MVC应用程序中使用java配置和自定义AuthenticationProvider吗?

在几个博客文章和SO问题中相对较好地讨论了这个问题.然而,我无法找到一个专门解决java配置问题的人.我怀疑我在java配置文件中做错了,因为我发现一些帖子表明可以通过删除调试XML标签来解决问题(https://jira.springsource.org/browse/ SEC-1885).

我正在使用Spring安全性的3.2.0.RELEASE和Spring框架的3.2.6.RELEASE.在spring security/mvc配置和自定义AuthenticationProvider中使用的主文件下面.

WebConfig:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.mypackage"})
@ImportResource( { "classpath:/spring-data.xml", "classpath:/trace-context.xml" })
@EnableTransactionManagement  
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Bean
    public StandardServletMultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() {
        return new GraphDatabaseFactory().newEmbeddedDatabase("target/temp.db");
    }

    @Bean
    public RepositoryInitializer repositoryInitializer() {
        return new RepositoryInitializer();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new         LocaleChangeInterceptor(); …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-security servlet-3.0 spring-java-config

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

Spring Boot中的Spring安全配置

我正在努力将Spring 3项目转换为Spring 4 + Spring Boot.我不知道这是否是正确的做法.我将Spring Security XML配置转换为基于Java的配置,如下所示:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated();
    http.formLogin()
            .defaultSuccessUrl("/afterLogin")
            .loginPage("/profiles/lognin/form")
            .failureUrl("/accessDenied")
            .and()
            .authorizeRequests()
            .regexMatchers("....")
            .hasRole("ROLE_USER")
            .antMatchers("....")
            .hasRole("ROLE_USER")
            //....
            ;
}

@Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder)
        throws Exception {
           authManagerBuilder.authenticationProvider(this.getDaoAuthenticationProvider());
}
   // ....
} 
Run Code Online (Sandbox Code Playgroud)

当我点击主页URL时,我得到了Spring Security默认登录弹出面板.在我看来,上面的配置没有生效,但Spring Boot中的默认Spring Security配置却没有.如果是这样,如何覆盖默认值?

spring-security spring-boot spring-java-config

6
推荐指数
1
解决办法
9308
查看次数

Siteminder的Spring Security Java配置

我有一个inMemoryAuthentication配置工作:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(
            AuthenticationManagerBuilder authenticationManagerBuilder)
            throws Exception {

        authenticationManagerBuilder //
            .inMemoryAuthentication() //
                .withUser("employee") //
                    .password("employee") //
                    .roles("RoleEmployee")
        ;

    }

    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // @formatter:off

        httpSecurity
            .authorizeRequests()
                .antMatchers("/login","/login.request","/logout").permitAll()
                .anyRequest().hasRole("RoleEmployee")
        .and()
            .formLogin()
                .loginPage("/login.request")
                .loginProcessingUrl("/login")
                .failureUrl("/login.request?error")
                .permitAll()
        .and()
            .logout()
                .logoutUrl("/logout")
                .permitAll()
                .logoutSuccessUrl("/login.request")
        ;

        // @formatter:on
    }
}
Run Code Online (Sandbox Code Playgroud)

我想现在使用Siteminder身份验证并将其更改为:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    private UserDetailsService …
Run Code Online (Sandbox Code Playgroud)

siteminder spring-mvc spring-security spring-java-config

6
推荐指数
1
解决办法
7878
查看次数

@PropertySource与spel一起使用(systemEnvironment和systemProperties)

我有src/main/resources以下文件

bpp-dev.properties
bpp-prod.properties
bpp-test.properties
Run Code Online (Sandbox Code Playgroud)

通过我的STS,我可以在两个位置定义密钥envB

  1. 如何在VM argument-DenvB=dev
  2. 如何Environment变量 envB价值 prod

如果在Configuration课堂上,我有以下内容。

@Configuration
@PropertySource("classpath:/com/manuel/jordan/properties/bpp-${envB}.properties")
public class PropertiesConfiguration {
Run Code Online (Sandbox Code Playgroud)

它工作正常,但始终优先于System Propertiesover Environment Variables,这是默认行为。我在这里没问题。

但是,如果我想与显式地工作Environment Variables,以下失败

@Configuration
@PropertySource("classpath:/com/manuel/jordan/properties/bpp-#{systemEnvironment['envB']}.properties")
public class PropertiesConfiguration {
Run Code Online (Sandbox Code Playgroud)

我总是收到:

Caused by: java.io.FileNotFoundException: 
class path resource 
[com/manuel/jordan/properties/bpp-#{systemEnvironment['envB']}.properties]
cannot be opened because it does not exist
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

如果我使用该功能@PropertySource并且只是在同一@Configuration堂课上玩,那么我将使用以下内容:

@Value("#{systemProperties['envB']}")
private String propertiesEnvB;
@Value("#{systemEnvironment['envB']}")
private String environmentEnvB;
Run Code Online (Sandbox Code Playgroud)

待稍后打印,两者都可以正常工作。

spring spring-3 spring-java-config spring-4

6
推荐指数
0
解决办法
1085
查看次数

什么相当于java config中的<tcp-outbound-channel-adapter>?

我有以下bean的spring集成XML配置

<int-ip:tcp-outbound-channel-adapter id="outboundClient"
channel="input"
connection-factory="client"/>
Run Code Online (Sandbox Code Playgroud)

我认为java配置中的等价物将是

@ServiceActivator(inputChannel = "input", requiresReply = "true")
public TcpSendingMessageHandler outboundClient() {
    TcpSendingMessageHandler tcpSendingMessageHandler = new TcpSendingMessageHandler();
    tcpSendingMessageHandler.setConnectionFactory(clientConnectionFactory());
    tcpSendingMessageHandler.setRetryInterval(10000);
    tcpSendingMessageHandler.setClientMode(true);
    return tcpSendingMessageHandler;
}
Run Code Online (Sandbox Code Playgroud)

但是,在日志中,我看到了

TcpListener exiting - no listener and not single use
Run Code Online (Sandbox Code Playgroud)

我无法收到服务器的回复.

任何帮助表示赞赏

java spring spring-integration spring-java-config

6
推荐指数
1
解决办法
1171
查看次数

实现AsyncConfigurer时,Spring异步不起作用

为异步方法提供Spring配置类:

@Configuration
@EnableAsync(proxyTargetClass = true)
@EnableScheduling
public class AsyncConfiguration {

@Autowired
private ApplicationContext applicationContext;

@Bean
public ActivityMessageListener activityMessageListener() {
    return new ActivityMessageListener();
}
@Bean
public TaskExecutor defaultExecutor()
{
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(10);
    threadPoolTaskExecutor.setMaxPoolSize(10);
    threadPoolTaskExecutor.setQueueCapacity(Integer.MAX_VALUE);

    return threadPoolTaskExecutor;
}
Run Code Online (Sandbox Code Playgroud)

我所有的@Async方法按预期工作,但如果我执行AsyncConfigurerAsyncConfiguration为了赶实施异常getAsyncUncaughtExceptionHandler()的方法,我的豆子没有被代理这样的方法@Async并不在池中执行运行.

这是非工作配置:

@Configuration
@EnableAsync(proxyTargetClass = true)
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {

@Autowired
private ApplicationContext applicationContext;

@Bean
public ActivityMessageListener activityMessageListener() {
    return new ActivityMessageListener();
}

@Override
public Executor getAsyncExecutor() { …
Run Code Online (Sandbox Code Playgroud)

spring asynchronous cglib spring-java-config spring-async

6
推荐指数
1
解决办法
6362
查看次数

AuthenticationCredentialsNotFoundException:在安全上下文中找不到Authentication对象

当我尝试将Chrome浏览器的POSTMAN插件中的JSON有效负载发送到作为REST URL公开的控制器时,我收到以下错误 - http:// localhost:8080/services/acc/create

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/services] threw exception [Request processing failed; nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext] with root cause
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:339)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:198)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:60)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at com.webadvisors.controller.HotelRestController$$EnhancerBySpringCGLIB$$e9f80d9.createHotel(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-java-config

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