Spring Framework 4.3 注入机制的改进

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2016/03/06/spring-framework-4-3-new/

Spring Framework 4.3有两个有趣的改动,第一个是单一构造函数的自动注入,第二个就是注入依赖条件的配置。

来看看之前版本的代码

@Service
public class FooService {

    private final FooRepository repository;

    @Autowired
    public FooService(FooRepository repository) {
        this.repository = repository
    }
}

@Autowired注解是一个很关键的东西,如果你忘记了,那么运行就会出现null错误。在新版本中,你无需这个注解了,Spring会自动处理这种情况。当然,这个功能同样对@Configuration等有效。

新的ObjectProvider可以提供两个特别的方法getIfAvailable和getIfUnique。比如这种

@Service
public class FooService {

    private final FooRepository repository;

    public FooService(ObjectProvider<FooRepository> repositoryProvider) {
        this.repository = repositoryProvider.getIfUnique();
    }
}

具体的实现可以参考DefaultListableBeanFactory,比如

public Object getIfUnique() throws BeansException
{
	DependencyDescriptor descriptorToUse = new DependencyDescriptor( descriptor )
	{
		@Override
		public boolean isRequired()
		{
			return(false);
		}


		@Override
		public Object resolveNotUnique( Class<?> type, Map<String, Object> matchingBeans )
		{
			return(null);
		}
	};
	if ( this.optional )
	{
		return(new OptionalDependencyFactory().createOptionalDependency( descriptorToUse, this.beanName ) );
	}else  {
		return(doResolveDependency( descriptorToUse, this.beanName, null, null ) );
	}
}

 

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2016/03/06/spring-framework-4-3-new/

发表评论