前言:
此时朋友们对“net framework 依赖注入”大约比较注重,小伙伴们都想要了解一些“net framework 依赖注入”的相关知识。那么小编也在网上网罗了一些对于“net framework 依赖注入””的相关资讯,希望姐妹们能喜欢,各位老铁们一起来学习一下吧!本篇我们一起来看一下Spring Framework IoC的字段依赖注入。这里我总结了以下几种方式:
* 手动模式 * Java 注解配置元信息 * @Autowired * @Resource * @Inject
字段的依赖注入只有手动的模式,并没有自动模式。接下来我们就一起通过实际的案例来实践一下。代码如下:
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.eleven.thinking.in.spring.ioc.dependency.injection;import org.eleven.thinking.in.spring.ioc.overview.domain.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import javax.annotation.Resource;/** * 基于 Java 注解的依赖字段注入示例 * * @author <a href="mailto:eleven.hm@vip.163.com">eleven</a> * @since */public class AnnotationDependencyFieldInjectionDemo { @Autowired private// static // @Autowired 会忽略掉静态字段 UserHolder userHolder; @Resource private UserHolder userHolder2; public static void main(String[] args) { // 创建 BeanFactory 容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); // 注册 Configuration Class(配置类) -> Spring Bean applicationContext.register(AnnotationDependencyFieldInjectionDemo.class); XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext); String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml"; // 加载 XML 资源,解析并且生成 BeanDefinition beanDefinitionReader.loadBeanDefinitions(xmlResourcePath); // 启动 Spring 应用上下文 applicationContext.refresh(); // 依赖查找 AnnotationDependencyFieldInjectionDemo Bean AnnotationDependencyFieldInjectionDemo demo = applicationContext.getBean(AnnotationDependencyFieldInjectionDemo.class); // @Autowired 字段关联 UserHolder userHolder = demo.userHolder; System.out.println(userHolder); System.out.println(demo.userHolder2); System.out.println(userHolder == demo.userHolder2); // 显示地关闭 Spring 应用上下文 applicationContext.close(); } @Bean public UserHolder userHolder(User user) { return new UserHolder(user); }}
以上就是我们通过字段的方式进行依赖注入的实践。这里需要注意的一个问题就是:@Autowired 会忽略掉静态字段。
版权声明:
本站文章均来自互联网搜集,如有侵犯您的权益,请联系我们删除,谢谢。
标签: #net framework 依赖注入