我想要与此 XML 配置等效的内容(在此处获取),但使用 Java 配置:
<bean id="customHandler" class="app.wsock.CustomHandler"/>
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/foo">
<websocket:handshake-handler ref="customHandler"/>
</websocket:stomp-endpoint>
<websocket:simpl-broker prefix="/topic,/queue" />
</websocket:message-broker>
Run Code Online (Sandbox Code Playgroud)
我的目标是构建一个类,根据某些标准限制与我的 STOMP 端点(即:他的 websocket)的连接。
我不想使用 XML 来配置我的端点,如何将该代码段转换为 Java Config?
--Appconfig.java
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
--interface.java
public interface HelloWorld {
void printHelloWorld(String msg);
}
Run Code Online (Sandbox Code Playgroud)
--ipml.java
public class HelloWorldImpl implements HelloWorld {
public void printHelloWorld(String msg) {
System.out.println("Hello! : " + msg);
--
}
Run Code Online (Sandbox Code Playgroud)
--App.java
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld) context.getBean(HelloWorldImpl.class);
obj.printHelloWorld("Spring3 Java Config");
}
}
Run Code Online (Sandbox Code Playgroud)
My program can works, but my question is why …
我有一个 java 配置,我使用一些属性创建 bean,在application.properties. 对于其中之一,我有一个很长的默认值,因此我将此值提取public static final String到此配置的字段中,现在我想将@Value其用作默认值。
所以最终我想要这样的东西:
@Configuration
public class MyConfiguration {
public static final String DEFAULT_PROPERTY_VALUE = "long string...";
@Bean("midPriceDDSEndpoint")
public DistributedDataSpace<Long, MidPriceStrategy> midPriceDDSEndpoint(
@Value("${foo.bar.my-property:DEFAULT_PROPERTY_VALUE}") String myPropertyValue) {
... create and return bean...
}
}
Run Code Online (Sandbox Code Playgroud)
但是到了春天就不是我的领域了,所以我很好奇我是否能以某种方式让它查找它。
解决此问题的一种方法是通过配置 bean: 访问此静态字段@Value(${foo.bar.my-property:#{myConfigurationBeanName.DEFAULT_PROPERTY_VALUE}}),但使用这种方法会使构造函数不可读,因为Value注释会占用大量空间(因为属性名称和配置 bean 名称在此示例中比此示例中更长)。有没有其他方法可以让 spring 使用静态字段作为属性的默认值?
每个函数的目的是什么。为什么spring给配置类赋予了两种不同的功能?我对两者感到困惑,我应该使用哪一个?
我想知道它是否只是我或者是Spring的Java配置的大多数例子有缺陷吗?比如这里:
http://spring.io/blog/2008/03/27/spring-java-configuration-what-s-new-in-m3 http://spring.io/blog/2013/07/18/javaconfig-support -in最弹簧工具套件
注意他们如何注入豆子?他们直接使用方法,例如:new OrderRepository(dataSource())here:
@Configuration
public class ApplicationConfig {
public @Bean OrderRepository orderRepository() {
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource() {
// instantiate and return an new DataSource ...
}
}
Run Code Online (Sandbox Code Playgroud)
这让我想到 - 如果两次使用它会不会创建两个对象?有效地绕过Spring的单身保证?他们为什么不注入豆类呢?因为依赖框架被设计为首先工作.
我们来做快速测试吧.以这两个类为例--TestParent和TestedChild.家长接受一个孩子:new TestParent(new TestedChild()).我们将在一分钟内制作单身豆.
public class TestedChild { }
public class TestParent {
private TestedChild child;
public TestParent(TestedChild child) {
this.child = child;
}
public TestedChild getChild() { return child; }
}
Run Code Online (Sandbox Code Playgroud)
我想看到的是,如果我们实际上可以获得在上下文初始化期间创建的两个不同的TestedChild实例.我们现在配置我们的单例bean:
@Configuration
public class TestInjectionConfig {
@Bean(name …Run Code Online (Sandbox Code Playgroud) 我只使用JavaConfig.
我有以下声明:
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Run Code Online (Sandbox Code Playgroud)
根据以下帖子,JavaConfig是必需的: 使用纯Java配置的Spring 3.2 @value注释不起作用,但Environment.getProperty可以正常工作
以下代码完美(许多@Values通过测试目的):
@Configuration
public class ActiveMQServerConfiguration {
@Value("${localhost.address}")
private String localHost;
@Value("${remotehost.address}")
private String remoteHost;
@Value("${localhost.port}")
private Integer localPort;
@Value("${remotehost.port}")
private Integer remotePort;
@Bean(name="connectionFactory")
@Conditional(LocalHostStatusCondition.class)
public ActiveMQConnectionFactory localConnectionFactory(
@Value("${localhost.protocol}") String protocol,
@Value("${localhost.address}") String host,
@Value("${localhost.port}") String port ){
System.out.println("protocol: "+protocol);
System.out.println("host: "+host);
System.out.println("port: "+port);
System.out.println("localHost: "+localHost);
System.out.println("localPort: "+localPort);
System.out.println("remoteHost: "+remoteHost);
System.out.println("remotePort: "+remotePort);
Run Code Online (Sandbox Code Playgroud)
我可以在控制台/终端中看到
Α
protocol: tcp
host: 127.0.0.1
port: 61616
localHost: 127.0.0.1
localPort: 61616
remoteHost: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用自定义进行URL授权AccessDecisionVoter.我没有收到任何错误,调试显示我的选民在启动时被选中.但是,在运行时,vote不会调用该方法,从而允许每个经过身份验证的用户完全访问.
请注意,我不需要方法安全性.我也没有使用XML配置.这排除了互联网上有关此主题的每个例子.
@Configuration
@EnableWebSecurity
@EnableWebMvc
@ComponentScan
@Order(-10)
public class HttpSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${trusted_ports}")
private List<Integer> trustedPorts;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private ServiceIdAwareVoter serviceIdAwareVoter;
RequestMatcher requestMatcher = new OrRequestMatcher(
// @formatter:off
new AntPathRequestMatcher("/**", GET.name()),
new AntPathRequestMatcher("/**", POST.name()),
new AntPathRequestMatcher("/**", DELETE.name()),
new AntPathRequestMatcher("/**", PATCH.name()),
new AntPathRequestMatcher("/**", PUT.name())
// @formatter:on
);
@Override
protected UserDetailsService userDetailsService() {
return userDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(preAuthProvider());
auth.authenticationProvider(authProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception …Run Code Online (Sandbox Code Playgroud) 我不需要Admin角色,所以我只需要执行身份验证.
@Configuration
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private MyAuthenticationSuccessHandler authenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login")
.successHandler(authenticationSuccessHandler).failureUrl("/login?error").permitAll().and().logout()
.permitAll();
http.csrf().disable();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select login, password, enabled from users where login=?");
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我尝试运行它时,我得到了
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,authority from authorities where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'phonebook.authorities' doesn't exist
Run Code Online (Sandbox Code Playgroud)
,这是合乎逻辑的,因为我没有.authoritiesByUsernameQuery()应用方法.问题是我该如何克服它?如何在不需要查询数据库的情况下为所有用户分配默认角色?如何仅使用登录名和密码从数据库登录,并且没有角色?
authentication authorization jdbc spring-security spring-java-config
我使用Spring 4.2.6.RELEASE和后端是休息服务.现在我无法使用Prevent XSS过滤器
我的过滤器是:
@Component
@Order(1)
public class XSSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
}
}
Run Code Online (Sandbox Code Playgroud)
和XSSRequestWrapper是:
public class XSSRequestWrapper extends HttpServletRequestWrapper {
public XSSRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
} …Run Code Online (Sandbox Code Playgroud) 在Spring Java配置中,假设我想@Bean在另一个@Bean定义中重复使用a 。我可以在一个文件中执行此操作:
@Bean
public A buildA() {
return new A();
}
@Bean
public B buildB() {
return new B(buildA());
}
Run Code Online (Sandbox Code Playgroud)
或者我可以在一个文件中配置A,然后在另一个文件中将其自动连接,例如(为简洁起见,请使用字段注入):
@Autowired
private A a;
@Bean
public B buildB() {
return new B(a);
}
Run Code Online (Sandbox Code Playgroud)
我想知道这两种可能性是否完全相同?对我来说,第一个版本可能会使A两次虚假,而第二个版本则不会。
我问这个问题,因为在我的特殊用例中,A正在建立与消息传递代理的连接,并且我有几个B在消耗流(我是.toReactivePublisher()从A中的Spring集成中使用的),并且我不想连接两次或更多给经纪人。
我使用 Spring 的时间很短,但对于 wicket 我是新手。但我想尝试一下这个框架。
我想一起配置这两个框架。但我想避免使用 xml 配置文件。
我知道检票口可以这样配置,根据:
http://wicket.apache.org/guide/guide/single.html#helloWorld_2 和这个:
https://github.com/bitstorm/Wicket-tutorial-examples/tree/master/SpringInjectionExample
但现在我只收到错误:
lis 15, 2014 4:31:15 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter com.derp.wicket.ProjectFilter
java.lang.NoSuchMethodError: org.apache.wicket.protocol.http.WebApplication.setMetaData(Lorg/apache/wicket/MetaDataKey;Ljava/lang/Object;)Lorg/apache/wicket/Application;
at org.apache.wicket.spring.injection.annot.SpringComponentInjector.<init>(SpringComponentInjector.java:115)
at org.apache.wicket.spring.injection.annot.SpringComponentInjector.<init>(SpringComponentInjector.java:92)
at com.derp.wicket.WicketApplication.init(WicketApplication.java:52)
at org.apache.wicket.Application.initApplication(Application.java:823)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:424)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:351)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4603)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5210)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:581)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1686)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
lis 15, 2014 4:31:15 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error …Run Code Online (Sandbox Code Playgroud) spring ×9
java ×5
spring-mvc ×2
annotations ×1
jdbc ×1
rest ×1
spring-3 ×1
spring-4 ×1
spring-boot ×1
stomp ×1
wicket ×1
xss ×1