您的位置:首页 > 编程语言 > Java开发

Spring学习笔记(一)

2015-10-24 21:40 288 查看

Spring学习笔记(一)

Spring核心思想:

IOC: Inversion Of Control (控制反转) / DI: Dependency Injection (依赖注入)

AOP: Aspect Oriented Programming (面向切面编程)

IOC

1. 简单的应用

Model

package com.wangj.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.wangj.spring.model.User;
import com.wangj.spring.service.UserService;

public class SpringDemo {
public static void main(String[] args) {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("config/applicationContext.xml");

UserService service = (UserService) applicationContext.getBean("userService");

User user = new User();
user.setUsername("wangj");
user.setPassword("wangj1130");
service.add(user);
}
}


View Code

2. 具体用法(XML配置)

bean注入方法

1. set方法注入

<bean id="userService" class="com.wangj.spring.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>

2. 构造方法注入
<bean id="userService" class="com.wangj.spring.service.UserService">
<constructor-arg>
<ref bean="userDao"/>
<!-- <bean class="com.wangj.test.spring.dao.impl.UserDaoImpl"/> --> <!-- 重新new对象 -->
</constructor-arg>
</bean>

当构造方法里含有多个参数时:
1)根据类型
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
2)根据顺序
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>


bean scope属性:

  scope="singleton" //(默认)每次使用同一个对象

     ="prototype" //每次都new一个新的(Struts Action)

     =request、session、global session(不重要)

集合注入

<bean name="userDAO" class="com.wangj.dao.impl.UserDAOImpl">
<property name="sets">
<set>
<value>1</value>
<value>2</value>
</set>
</property>
<property name="lists">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<property name="maps">
<map>
<entry key="1" value="1"></entry>
<entry key="2" value="2"></entry>
<entry key="3" value="3"></entry>
<entry key="4" value="4"></entry>
</map>
</property>
</bean>


autowire 自动装配

  autowire="byName" // 根据名称自动装配,该名称为setXxx()方法中xxx(set后的字符串首字母小写),与变量名无关

      ="byType" // 根据类型自动装配

      ="default" // 跟<beans 节点中 default-autowire属性一致,如果<beans节点中未配置default-autowire属性,则报异常

bean生命周期

  lazy-init="true" // 什么时用到什么时候初始化(sping初始化默认将所有bean加载到内存)

  init-method="init" // 容器初始化时调用

  destroy-method="destroy" // 容器销毁时调用

  (init-method、destroy-method 一般不和prototype一起用)

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: