Spring ioc
来源:互联网 发布:海口网站排名优化 编辑:程序博客网 时间:2024/06/15 10:18
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//启动spring容器/** ApplicationContext:接口。* ClassPathXmlApplicationContext:是* 实现了AppliationContext接口的类。* 注意:配置文件的路径和文件名,spring* 容器在启动时,需要读取配置文件。*/让容器创建对象
方式一: 使用无参构造器。(重点)
step1. 为类提供一个无参构造器(缺省构造器)
step2. 在配置文件当中,添加一个bean元素。
step3. 启动spring容器,调用getBean方法来获得对象。
set方法的ioc注入
在配置文件中写
<bean id="c1" class="ioc.C"/><bean id="a1" class="ioc.A"><property name="b" ref="c1"/></bean>
在类A中注入 C的set方法
<util:properties id="config" location="classpath:config.properties"/>
使用:
1.用test测试
@Testpublic void test2(){System.out.println(ac.getBean("config"));}
2.使用value注解
@Value("#{config.pagesize}")private String pageSize;
<util:list id="citiesBean"><value>北京</value><value>岳阳</value><value>华容</value></util:list><util:set id="interestBean"><value>游泳</value><value>做饭</value><value>画画</value></util:set><util:map id="scoreBean"><entry key="english" value="80"/><entry key="math" value="90"/></util:map><util:properties id="dbBean"><prop key="username">Sally</prop><prop key="password">1234</prop></util:properties><!-- 引用的方式注入集合类型的值 --><bean id="eb2" class="value.ExampleBean"><property name="cities" ref="citiesBean"/><property name="interest" ref="interestBean"/><property name="score" ref="scoreBean"/><property name="db" ref="dbBean"/></bean>
使用注解来住入
容器启动之后,如果发现配置文件有component-scan元素, 则容器会扫描相应的包及其子包下面的所有的类,如果这些 类前面有一些特殊的注解(比如@Component),则容器会将 这些类纳入容器进行管理(相当于以前配置文件当中有相应的 bean元素)。
注:bean的默认id是首字母小写之后的类名。
@Component 通用
@Service 业务层
@Repository 持久层
@Controller 控制层
(3)生命周期相关的两个注解:
@PostConstruct 初始化
@PreDestroy 销毁
(4)用于延迟加载的注解:
@Lazy(true) true表示延迟加载。
(5)用于指定作用域的注解:
@Scope(“prototype”)。
依赖注入相关的注解
@Autowired 和 @Qualifier
a. 支持set方式的注入和构造器方式的注入。
b. set方式注入:
将@Autowired和@Qualifer加到set方法前面, 也可以加到属性前面。其中,@Qualifer用于指定 要注入的bean的id。
注:如果不指定id,则使用byType的方式来注入。
@Resource
a. 只支持set方式的注入。
b. 可以将该注解加到set方法前面,或者也可以加到 属性前。使用name属性来指定要注入的bean的id。
@value注解即可以用在属性前,也可以用在 set方法前。另外,也可以使用该注解注入基本类 型的值。
- IOC、Spring的IOC
- Spring IoC
- [Spring]IoC
- Spring IOC
- Spring IOC
- spring IOC
- Spring IOC
- Spring IOC
- Spring Ioc
- Spring IoC
- spring ioc
- Spring IOC
- spring IOC
- Spring Ioc
- Spring IoC
- Spring IOC
- Spring IOC
- Spring IoC
- 没有为扩展名.htm注册的生成提供程序,没有为扩展名.html注册的生成提供程序
- MySQL grant指令详解
- Gradle for Android应用
- mysql总结
- Kafka-0.10.1.0 简单安装部署
- Spring ioc
- Comparable与Comparator的比较
- Horizon 源码阅读(三)—— Horizon 用户登录流程
- 转义的理解,replace和replaceAll的区别
- androidStudio适应期:as中联想代码快捷键以及查看错误窗口
- android 中shape的使用
- IOS 模拟器显示不全问题
- zookeeper的简单使用
- socket相关知识点