使用Spring的Java Config,我需要使用只能在运行时获得的构造函数参数来获取/实例化原型范围的bean.请考虑以下代码示例(为简洁起见而简化):
@Autowired
private ApplicationContext appCtx;
public void onRequest(Request request) {
//request is already validated
String name = request.getParameter("name");
Thing thing = appCtx.getBean(Thing.class, name);
//System.out.println(thing.getName()); //prints name
}
Run Code Online (Sandbox Code Playgroud)
Thing类的定义如下:
public class Thing {
private final String name;
@Autowired
private SomeComponent someComponent;
@Autowired
private AnotherComponent anotherComponent;
public Thing(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
注意事项name是final:它只能通过构造函数来提供,并保证不变性.其他依赖项是Thing类的特定于实现的依赖项,并且不应该知道(紧密耦合到)请求处理程序实现.
此代码与Spring XML配置完美配合,例如:
<bean id="thing", class="com.whatever.Thing" scope="prototype">
<!-- other post-instantiation properties omitted --> …Run Code Online (Sandbox Code Playgroud) 我们将Spring Boot/MVC与基于注释的java-config一起用于一系列RESTful服务,我们希望有选择地HTTP GZIP在某些API响应上启用流压缩.
我知道我可以在我的控制器中手动执行此操作byte[] @ResponseBody,但是我们更愿意依赖SpringMVC基础结构(过滤器/等)并让它自动执行JSON转换和压缩(即该方法返回POJO).
如何在ResponseBody或嵌入式Tomcat实例中启用GZIP压缩,并且我们可以选择性地仅压缩某些响应?
谢谢!
PS.:我们目前没有任何基于XML的配置.
我正在使用Spring Security 3.2和Spring 4.0.1
我正在努力将xml配置转换为Java配置.当我在我的过滤器中注释AuthenticationManager时@Autowired,我得到一个例外
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过注射AuthenticationManagerFactoryBean但是也失败了类似的例外.
这是我正在使用的XML配置
<?xml version="1.0" encoding="UTF-8"?> <beans ...>
<security:authentication-manager id="authenticationManager">
<security:authentication-provider user-service-ref="userDao">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<security:http
realm="Protected API"
use-expressions="true"
auto-config="false"
create-session="stateless"
entry-point-ref="unauthorizedEntryPoint"
authentication-manager-ref="authenticationManager">
<security:access-denied-handler ref="accessDeniedHandler"/>
<security:custom-filter ref="tokenAuthenticationProcessingFilter" position="FORM_LOGIN_FILTER"/>
<security:custom-filter ref="tokenFilter" position="REMEMBER_ME_FILTER"/>
<security:intercept-url method="GET" pattern="/rest/news/**" access="hasRole('user')"/>
<security:intercept-url method="PUT" pattern="/rest/news/**" access="hasRole('admin')"/>
<security:intercept-url method="POST" …Run Code Online (Sandbox Code Playgroud) 我有一个Spring Boot web应用程序,配置了spring security.我想暂时禁用身份验证(直到需要).
我把它添加到application.properties:
security.basic.enable: false
management.security.enabled: false
Run Code Online (Sandbox Code Playgroud)
这是我的一部分
但我仍然有一个基本的安全性:启动时生成一个默认的安全密码,我仍然收到HTTP身份验证提示框.
我的pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.test.sample</groupId>
<artifactId>navigo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<java.version>1.7</java.version>
<jsoup.version>1.8.3</jsoup.version>
<guava.version>18.0</guava.version>
<postgresql.version>9.3-1103-jdbc41</postgresql.version>
</properties>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> …Run Code Online (Sandbox Code Playgroud) 我正在使用带有Java配置的Spring-Security 3.2.0.RC2.我设置了一个简单的HttpSecurity配置,要求/ v1/**上的基本身份验证.GET请求工作但POST请求失败:
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
Run Code Online (Sandbox Code Playgroud)
我的安全配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private MyUserDetailsService userDetailsService;
@Autowired
//public void configureGlobal(AuthenticationManagerBuilder auth)
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
StandardPasswordEncoder encoder = new StandardPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
@Configuration
@Order(1)
public static class RestSecurityConfig
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/v1/**").authorizeRequests()
.antMatchers("/v1/**").authenticated()
.and().httpBasic();
}
}
}
Run Code Online (Sandbox Code Playgroud)
对此的任何帮助都非常感谢.
post csrf spring-security basic-authentication spring-java-config
我是Spring MVC框架的新手,我遇到了一个我自己无法解决的问题.一切都是在我将spring security与我的应用程序集成后开始的,之后HTML表单中的所有unicode值都没有编码(spring security工作正常).我得出的结论是,这可能是因为我DelegatingFilterProxy被称为链中的第一个过滤器.
这是我认为可以使用的配置,但它没有:
1)我正在从javadoc扩展AbstractSecurityWebApplicationInitializer:
Registers the DelegatingFilterProxy to use the springSecurityFilterChain() before any
other registered Filter.
Run Code Online (Sandbox Code Playgroud)
从那个类我也覆盖了关于javadoc的SpringSecurityFilterChain方法:
Invoked before the springSecurityFilterChain is added.
Run Code Online (Sandbox Code Playgroud)
所以我认为这将是注册CharacterEncodingFilter的最佳位置:
public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter());
characterEncodingFilter.setInitParameter("encoding", "UTF-8");
characterEncodingFilter.setInitParameter("forceEncoding", "true");
characterEncodingFilter.addMappingForUrlPatterns(null, true, "/*");
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
我厌倦的另一个选择是通过覆盖getServletFilters()方法通过AbstractAnnotationConfigDispatcherServletInitializer类注册过滤器:
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//{!begin addToRootContext}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { SecurityConfig.class, DatabaseConfig.class, InternationalizationConfig.class };
}
//{!end …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Springs java-config为我的应用程序上下文运行Junit功能测试.我不确定它是否是Spring或Junit的问题...只是不确定..应用程序在我的本地服务器上运行正常(击中数据库),但是当我尝试运行我的测试时它会爆炸.我刚刚从xml移动到java配置,所以我总是可以导入我的xml上下文文件(我知道在我的测试中可以工作),但是我想继续使用我的java配置.
我的测试班
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = { AppConfig.class, ServletConfig.class })
@EnvironmentConfiguration(db2Enabled = true)
public class EventDAOTest {
Run Code Online (Sandbox Code Playgroud)
StackTrace
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader <clinit>
SEVERE: ERROR - Configuration Framework not detected!
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader readFile
SEVERE: Unable to build property reference for: (common).
2014-02-04 11:51:45,510 | DEBUG | : | LoggerConfigurer | Msg: Log4j configured with: 'C:/javalog/log4jPCProperties.xml'
2014-02-04 11:51:48,248 | INFO | : | EnvironmentConfigurer | Msg: DB2 Connection was established
2014-02-04 11:51:48,279 …Run Code Online (Sandbox Code Playgroud) 有没有办法授权使用特定网址的帖子请求org.springframework.security.config.annotation.web.builders.HttpSecurity?
我用的HttpSecurity是:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.rememberMe()
.rememberMeServices(rememberMeServices)
.key(env.getProperty("jhipster.security.rememberme.key"))
.and()
.formLogin()
.loginProcessingUrl("/api/authentication")
.successHandler(ajaxAuthenticationSuccessHandler)
.failureHandler(ajaxAuthenticationFailureHandler)
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/subscriptions").permitAll()
.antMatchers("/api/**").authenticated();
}
Run Code Online (Sandbox Code Playgroud)
我想允许POST请求到/ api/subscription路径.只有POST.谢谢.
Spring Security <custom-filter>标记的等效Java配置是什么?
<http>
<custom-filter position="FORM_LOGIN_FILTER" ref="myFilter"/>
</http>
Run Code Online (Sandbox Code Playgroud)
我试过了
http.addFilter( new MyUsernamePasswordAuthenticationFilter() )
Run Code Online (Sandbox Code Playgroud)
类扩展默认过滤器,但它始终使用默认过滤器formLogin.
我的过滤器:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
// proof of concept of how the http.addFilter() works
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
System.out.println("running my own version of UsernmePasswordFilter ... ");
String username = …Run Code Online (Sandbox Code Playgroud) 我的主要工作只是读取操作而另一个人写了一些但MyISAM engine忽略了事务,所以我不需要事务支持.如何配置Spring Batch拥有自己的数据源JobRepository,与持有业务数据的数据源分开?最初的一个数据源配置如下所示:
@Configuration
public class StandaloneInfrastructureConfiguration {
@Autowired
Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.podcastpedia.batch.*" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalJpaProperties());
return em;
}
Properties additionalJpaProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "none");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
@Bean
public DataSource dataSource(){
return DataSourceBuilder.create()
.url(env.getProperty("db.url"))
.driverClassName(env.getProperty("db.driver"))
.username(env.getProperty("db.username"))
.password(env.getProperty("db.password"))
.build();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = …Run Code Online (Sandbox Code Playgroud) spring ×6
java ×5
spring-boot ×2
spring-mvc ×2
csrf ×1
gzip ×1
jhipster ×1
junit4 ×1
post ×1
prototype ×1
rest ×1
scope ×1
spring-batch ×1