Spring学习笔记_IOC

Spring简介

1,   只用IOC

spring.jar , jarkata-commons/commons-loggin.jar

2,IOC容器

实例化具体bean

动态装配

3,AOP支持

安全检查

管理transaction

Spring配置

1,注入类型

  •   setter(重要)
  • 构造方法(可以忘记)
  •     接口注入(可以忘记)
<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"><!-- new UserDAOImpl()-->
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService">
      <!--
      <property name="userDAO" ref="u" />  setter注入 ,调用setxxx方法
       -->
       <constructor-arg>  <!-- 构造方法注入,需要在UserService里面写构造方法,相当于调用了构造方法-->
           <ref bean="u"/>   <!-- 参考了另外一个已经new 的bean-->
       </constructor-arg>
  </bean>
public class UserService {

    private UserDAO userDAO;
    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public UserService(UserDAO userDAO) {//用于构造方法注入
        super();
        this.userDAO = userDAO;
    }
}

2,id vs. name

  name可以用特殊字符

<bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService">
      <!--
      <property name="userDAO" ref="u" />
       -->
       <constructor-arg>
           <ref bean="u"/>
       </constructor-arg>
  </bean>

3,简单属性的注入

bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
      <property name="daoId" value="8"></property>
      <property name="daoStatus" value="good"></property>
  </bean>
public class UserDAOImpl implements UserDAO {
    private int daoId;
    private String daoStatus;

    public int getDaoId() {
        return daoId;
    }

    public void setDaoId(int daoId) {
        this.daoId = daoId;
    }

    public String getDaoStatus() {
        return daoStatus;
    }

    public void setDaoStatus(String daoStatus) {
        this.daoStatus = daoStatus;
    }

    public void save(User user) {
        System.out.println("user saved!");
    }

    @Override
    public String toString() {
        return this.daoId + ":" + this.daoStatus;
    }
}

4,bean 中的scope属性

  singleton:只有一个

  prototype:每一个都不同

5,集合注入

  很少用,不重要!

public class UserDAOImpl implements UserDAO {
    /* (non-Javadoc)
     * @see com.bjsxt.dao.UserDAO#save(com.bjsxt.model.User)
     */
    private Set<String> sets;
    private List<String> lists;
    private Map<String , String> maps;

    public Set<String> getSets() {
        return sets;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public UserDAOImpl() {
    }

    public void save(User user) {
        System.out.println("user saved!");
    }

    @Override
    public String toString() {
        return "sets size:" + sets.size() + "| lists size:" + lists.size() + "| maps size:" + maps.size() ;
    }

}
<bean name="userDAO" class="com.bjsxt.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>

  <bean id="userService" class="com.bjsxt.service.UserService">
  <!--
      <property name="userDAO">
          <ref bean="userDAO"/>
      </property>
       -->
       <constructor-arg>
           <ref bean="userDAO"/>
       </constructor-arg>
  </bean>

6,自动装配

  • byName
  • byType
  • 如果所有的bean都用同一种,可以使用beans的属性:default-autowire
 <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
      <property name="daoId" value="1"></property>
  </bean>

  <bean name="userDAO2" class="com.bjsxt.dao.impl.UserDAOImpl">
      <property name="daoId" value="2"></property>
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byName"> <!-- 未指定property, 若是byname则自动匹配name等于userDAO的bean, 若是bytype则匹配类型为userDAO的bean-->
  </bean>
public class UserDAOImpl implements UserDAO {

    private int daoId;

    public int getDaoId() {
        return daoId;
    }

    public void setDaoId(int daoId) {
        this.daoId = daoId;
    }

    public void save(User user) {

        System.out.println("user saved!");
    }

    @Override
    public String toString() {
        return "daoId=" + daoId;
    }

}

7,生命周期

  • lazy-init (不重要)  容器初始化时(ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml")),不初始化,只有用到时才初始化
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
  • init-method destroy-methd 不要和prototype一起用(了解)
<bean id="userService" class="com.bjsxt.service.UserService" init-method="init" destroy-method="destroy" scope="singleton">
      <!--
      <property name="userDAO" ref="u" />
       -->
       <constructor-arg>
           <ref bean="u"/>
       </constructor-arg>
  </bean>
public class UserService {

    private UserDAO userDAO;  

    public void init() {
        System.out.println("init");
    }

    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public UserService(UserDAO userDAO) {
        super();
        this.userDAO = userDAO;
    }

    public void destroy() {
        System.out.println("destroy");
    }
}

8,Annotation第一步:

修改xml文件,参考文档<context:annotation-config />

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
  <bean id="u2" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService" >

  </bean>

</beans>

9,@Autowired(自动装配)

  • 默认按类型by type
  • 如果想用byName,使用@Qulifier
  • 写在private field(第三种注入形式)(不建议,破坏封装)
  • 如果写在set上,@qualifier需要写在参数上
public class UserService {

    private UserDAO userDAO;  

    public void init() {
        System.out.println("init");
    }

    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }

    @Autowired
    public void setUserDAO(@Qualifier("u") UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void destroy() {
        System.out.println("destroy");
    }
}

10,@Resource(重要)

  • 加入:j2ee/common-annotations.jar
  • 默认按名称,名称找不到,按类型  @Resource
  • 可以指定特定名称  @Resource(name="u2")
  • 推荐使用
  • 不足:如果没有源码,就无法运用annotation,只能使用xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
  <bean id="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
  <bean id="u2" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>

  <bean id="userService" class="com.bjsxt.service.UserService" >

  </bean>

</beans>
public class UserService {

    private UserDAO userDAO;  

    public void init() {
        System.out.println("init");
    }

    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }
    @Resource(name="u2")
    //@Resource
    public void setUserDAO( UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void destroy() {
        System.out.println("destroy");
    }
}

11,@Component @Service @Controller @Repository  在spring2.5.6中 这四个目前没有区别

  • 初始化的名字默认为类名首字母小写
  • 可以指定初始化bean的名字 @Component("u")
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.bjsxt"/>
</beans>
@Component("u") //u=new UserDAO()
public class UserDAOImpl implements UserDAO {

    public void save(User user) {

        System.out.println("user saved!");
    }

}
@Component("userService")
public class UserService {

    private UserDAO userDAO;  

    public void init() {
        System.out.println("init");
    }

    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }

    @Resource(name="u") //把name=u的UserDAO注入
    public void setUserDAO( UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void destroy() {
        System.out.println("destroy");
    }
}

12,@Scope

13,@PostConstruct = init-method; @PreDestroy = destroy-method;

@Scope("singleton")
@Component("userService")
public class UserService {

    private UserDAO userDAO;  

    @PostConstruct
    public void init() {
        System.out.println("init");
    }

    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }

    @Resource(name="u")
    public void setUserDAO( UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @PreDestroy
    public void destroy() {
        System.out.println("destroy");
    }
}
时间: 2024-12-29 19:31:10

Spring学习笔记_IOC的相关文章

Spring学习笔记(一)

Spring学习笔记(一) Spring核心思想: IOC:  Inversion Of Control (控制反转) / DI: Dependency Injection (依赖注入) AOP: Aspect Oriented Programming (面向切面编程) IOC 1. 简单的应用 Model package com.wangj.spring.model; public class User { private String username; private String pas

不错的Spring学习笔记(转)

Spring学习笔记(1)----简单的实例 ---------------------------------   首先需要准备Spring包,可从官方网站上下载.   下载解压后,必须的两个包是spring.jar和commons-logging.jar.此外为了便于测试加入了JUnit包.   在Myeclipse中创建Java项目.   编写一个接口类,为了简单,只加入了一个方法.   Java代码   1.package com.szy.spring.interfacebean;  

《Spring学习笔记》:Spring、Hibernate、struts2的整合(以例子来慢慢讲解,篇幅较长)

<Spring学习笔记>:Spring.Hibernate.struts2的整合(以例子来慢慢讲解,篇幅较长) 最近在看马士兵老师的关于Spring方面的视频,讲解的挺好的,到了Spring.Hibernate.struts2整合这里,由于是以例子的形式来对Spring+Hibernate+struts2这3大框架进行整合,因此,自己还跟着写代码的过程中,发现还是遇到了很多问题,因此,就记录下. 特此说明:本篇博文完全参考于马士兵老师的<Spring视频教程>. 本篇博文均以如下这

spring学习笔记(19)mysql读写分离后端AOP控制实例

在这里,我们接上一篇文章,利用JNDI访问应用服务器配置的两个数据源来模拟同时操作不同的数据库如同时操作mysql和oracle等.实际上,上个例子可能用来模拟mysql数据库主从配置读写分离更贴切些.既然如此,在本例中,我们就完成读写分离的模拟在web端的配置实例. 续上次的例子,关于JNDI数据源的配置和spring datasource的配置这里不再重复.下面着重加入AOP实现DAO层动态分库调用.可先看上篇文章<spring学习笔记(18)使用JNDI模拟访问应用服务器多数据源实例 >

Spring学习笔记(三)

Spring学习笔记(三) AOP 一.使用Annotation方式实现AOP.步骤: xml里加入配置:<aop:aspectj-autoproxy /> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org

Spring学习笔记--initmethod和构造函数、setter方法的加载顺序

今天学习了一下spring中bean的初始化和销毁,突然想了解一下初始化方法跟构造函数及setter方法注入的执行顺序,记录在此,仅作为学习笔记. 当实例化一个bean时,可能需要执行一些初始化操作来确保该bean处于可用状态.同样地,当不再需要bean时,将其从容器中移除是,我们可以还需要按顺序 执行一些清除工作. package com.zp.chapter2; public class Auditorium { private String name; public void doBefo

【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展

<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www.cnblogs.com/ssslinppp/p/4528892.html [Spring学习笔记-MVC-4]返回Json数据-方式2:http://www.cnblogs.com/ssslinppp/p/4530002.html [Spring学习笔记-MVC-3.1]SpringMVC返回Json数据-

Spring学习笔记 2014-7-9

Spring需要applicationContext.xml来管理各个Bean,其基本格式: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t

Spring学习笔记一(Spring核心思想)

通过学习<Spring in action (Third edition)>的第一章,我大概了解了Spring的基本思想: 1,依赖注入(Dependnecy Injection): 在不使用Spring框架的情况下,一个类要跟另一个类建立联系,可能会使用如下的模式: class A{...} class B{ private A a; ...       } 这样的话,每次实例化一个B的对象,如b1,必定实例化一个A的对象,如a1,并且b1和a1是紧耦合的,b1牢牢地和a1绑定在一起了.他们