是否有一些关于如何通过java配置配置MailSender的示例?我见过的所有示例都使用xml来创建所需的bean:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="customerservice@mycompany.com"/>
<property name="subject" value="Your order"/>
</bean>
Run Code Online (Sandbox Code Playgroud) 我现在有一些体验Spring,并且还有一些纯Java配置web-apps正在使用中.但是,这些通常基于一个安静的简单设置:
对于我当前的项目,我需要具有不同配置的单独调度程序上下文.这不是基于XML的配置的问题,因为我们有一个独立于Dispatcher Configuration的专用ContextLoaderListener.但是使用java配置我不确定到目前为止我做的是否正常;)
这是一个常见的DispatcherConfig:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new class[]{MyAppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{MyDispatcherConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/mymapping/*"};
}
@Override
protected String getServletName() {
return "myservlet";
}
}
Run Code Online (Sandbox Code Playgroud)
如上所述,我需要第二个(第三个,......)调度程序与另一个映射(和视图解析器).因此,我复制了配置并添加了两个getServletName()(否则两者都将被命名为'dispatcher',这将导致错误).第二个配置看起来像这样:
public class AnotherWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new class[]{MyAppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{AnotherDispatcherConfig.class};
}
@Override
protected String[] getServletMappings() {
return …Run Code Online (Sandbox Code Playgroud) 要点是Spring Batch(v2)测试框架JobLauncherTestUtils.setJob带有@Autowired注释.我们的测试套件有多个Job类提供者.由于这个类不是我可以修改的,所以我不确定如何确定它自动装配的工作,每个测试可能会有所不同.
STDOUT [WARN ] [2015.04.15 11:14:42] support.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherTestUtilsForSnapshot': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.batch.test.JobLauncherTestUtils.setJob(org.springframework.batch.core.Job); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.Job] is defined: expected single matching bean but found 2: coverageRuleBatch,generateMetricsSnapshotJob
Run Code Online (Sandbox Code Playgroud)
我已经尝试添加这个被识别的JavaConfig,但是错误说它仍然是自动调用的 setJob
@Configuration
public class SpringTestConfiguration
{
@Bean
public JobLauncherTestUtils jobLauncherTestUtilsForSnapshot( final Job …Run Code Online (Sandbox Code Playgroud) 这是我的自定义验证器,用于检查某些字段的可用性.UserRepository为null,因此验证器不会注入它.
public class AvailableValidator implements ConstraintValidator<Available,String> {
@Autowired
private UserRepository userRepository;
private Available.Field type;
public void initialize(Available usernameAvailable) {
this.type = usernameAvailable.type();
}
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (userRepository == null) System.out.println("\n\n------USER REPOSITORY IS NULL-------\n\n");
switch (type){
case EMAIL:
return userRepository.findByEmail(s)==null;
case NUMBER:
return userRepository.findByNumber(s)==null;
case NAME:
return userRepository.findByName(s)==null;
default:
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经阅读了类似的线程,我必须设置验证工厂.我这样做了:
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
@Bean
public Validator validator(){
return new LocalValidatorFactoryBean();
} …Run Code Online (Sandbox Code Playgroud) validation spring dependency-injection spring-boot spring-java-config
目前我正在将xml转换为java配置.但我坚持了几天,我已经研究了几天.这里的问题是:
Xml配置:
<jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}" resource-ref="true" />
<beans:bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate" >
<beans:property name="dataSource" ref="dbDataSource"></beans:property>
</beans:bean>
Run Code Online (Sandbox Code Playgroud)
到目前为止,我设法转换此代码:
<jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}" resource-ref="true" />
对此:
@Bean(name = "dbDataSource")
public JndiObjectFactoryBean dataSource() {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("${db.jndi}");
bean.setResourceRef(true);
return bean;
}
Run Code Online (Sandbox Code Playgroud)
还有这个 :
<beans:bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate" >
<beans:property name="dataSource" ref="dbDataSource"></beans:property>
</beans:bean>
Run Code Online (Sandbox Code Playgroud)
对此:
@Bean(name = "jdbcTemplate")
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
return jt;
}
Run Code Online (Sandbox Code Playgroud)
问题是该方法的setDataSource()需要DataSource对象,但我不知道如何与两个bean.How到JndiObjectFactoryBean中传递给数据源?
或者我需要使用其他方法吗?
额外问题:
的bean.setJndiName("${db.jndi}"),$ {} db.jndi是指属性文件,但我总是得到的NameNotFoundException,如何使它工作?
谢谢!!
我在Spring Security中使用以下Java Config:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
Run Code Online (Sandbox Code Playgroud)
根据此配置,所有请求都经过身份验证.当您在未经过身份验证的情况下点击控制器时,AnonymousAuthenticationFilter将为您创建一个Authentication对象username=anonymousUser, role=ROLE_ANONYMOUS.
我试图提供对特定控制器方法的匿名访问,并尝试使用以下各项:
@Secured("ROLE_ANONYMOUS")@Secured("IS_AUTHENTICATED_ANONYMOUSLY")调用控制器方法时,会给出以下响应:"HTTP状态401 - 访问此资源需要完全身份验证"
有人可以帮助我理解为什么我们收到此消息以及为什么ROLE_ANONYMOUS/ IS_AUTHENTICATED_ANONYMOUSLY似乎没有使用此配置?
谢谢,
JP
使用JavaConfig我在查找@RepositorySpring bean时遇到问题.
存储库接口定义如下:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
Run Code Online (Sandbox Code Playgroud)
配置定义如下:
@Configuration
@ComponentScan("com.example")
@EnableAutoConfiguration
@EnableJpaRepositories("com.example")
public class SampleApplication extends SpringBootServletInitializer {
...
Run Code Online (Sandbox Code Playgroud)
包结构如下所示:
com.example
configuration
SampleApplication
repository
UserRepository
Run Code Online (Sandbox Code Playgroud)
在日志文件中,我看到存储库被认为是bean定义的候选者,但是:
ClassPathBeanDefinitionScanner | Ignored because not a concrete top-level class:
Run Code Online (Sandbox Code Playgroud)
趣味事实
如果我将SampleApplication类移动到com.example包,一切都开始工作.
我缺少什么想法?
假设我们有一个可以为某些客户定制的应用程序.该应用程序使用基于Java的弹簧配置(也称为Java配置)进行依赖注入.该应用程序由模块及其子模块组成.每个模块和子模块都有自己的@Configuration类,由父配置使用导入@Import.这将创建以下层次结构:
MainConfig
----------+---------------- ....
| |
ModuleAConfig ModuleBConfig
|--------------------|
| |
SubModuleA1Config SubModuleA2Config
Run Code Online (Sandbox Code Playgroud)
例如,ModuleAConfig看起来像这样:
@Configuration
@Import({SubModuleA1Config.class, SubModuleA2Config.class})
public class ModuleAConfig {
// some module level beans
}
Run Code Online (Sandbox Code Playgroud)
假设SubModuleA1Config定义someBean了SomeBean类型的bean:
@Configuration
public class SubModuleA1Config {
@Bean
public SomeBean someBean() { return new SomeBean(); }
}
Run Code Online (Sandbox Code Playgroud)
现在我想为Customer1(C1)定制应用程序 - 我想使用C1SomeBean(扩展SomeBean)而不是SomeBeanas someBean.
如何以最少的重复实现这一目标?
我的一个想法是准备C1Config继承自MainConfig,C1ModuleAConfig来自ModuleAConfig和C1SubModuleA1Config来自的替代层次结构SubModuleA1Config.C1SubModuleA1Config会覆盖 …
在以前版本的OAuth2中,可以通过将自定义标记granter添加到<authorization-server>元素中的xml配置来添加它.
我想知道如何使用AuthorizationServerConfigurerAdapter使用Java Config扩展授权服务器,而不会丢失包含隐式,客户端凭据,刷新令牌和授权代码授权类型的默认配置.
首次尝试使用@Component创建TokenGranter:
@Component("customTokenGranter")
public class CustomTokenGranter {
//implementation
}
Run Code Online (Sandbox Code Playgroud)
这导致依赖性解决异常,因为构造Granter所需的tokenServices无法自动装配.
第二次尝试使用configure方法
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
endpoints
.tokenGranter(new CustomTokenGranter(endpoints.getTokenServices(),
endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
}
Run Code Online (Sandbox Code Playgroud)
使用此选项,将不会注册默认授权类型.
我也尝试了低阶的第二种配置,但没有成功.我还可以做些什么来添加自定义授权类型?
我想使用Spring Framework的动态语言支持.
在XML我只用了lang命名空间,但我想使用Java配置(即@Configuration类)只.
我可以想象我可以通过初始化org.springframework.scripting.configpackage,inc中的所有地狱来做到这一点.他们创造的所有BeanPostProcessors,Handlers,Parsers和FactoryBeans,但我真的不想去那里.
还有其他方法吗?如果没有,那么从Groovy脚本创建可重新加载的bean所需的最小配置是什么?
spring ×10
java ×7
spring-boot ×2
email ×1
spring-3 ×1
spring-batch ×1
spring-data ×1
spring-mvc ×1
validation ×1