原文链接:http://www.orlion.ga/216/

一、@Autowired

beans.xml配置成如下:

<?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:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>
    <bean id="userDao" class="ml.orlion.dao.impl.UserDAOImpl">
    </bean>
    
    <bean id="userService" class="ml.orlion.service.UserService">
    </bean>
</beans>

当我们在配置文件中配置了<context:annotation-config/>时,spring会自动帮我们初始化四个bean(AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor)来处理我们在代码中的注解

然后UserService.java:

代码中的注解@Autowired默认是byType,所以beans.xml中不能出现两个类型相同的bean,因为如果类型一致spring就不知道应该注入哪一个了。

package ml.orlion.service;

import org.springframework.beans.factory.annotation.Autowired;

import ml.orlion.dao.UserDAO;
import ml.orlion.dao.impl.UserDAOImpl;
import ml.orlion.model.User; public class UserService {     private UserDAO userDAO = new UserDAOImpl();     public UserDAO getUserDao() {
        
        return userDAO;
    }
    @Autowired
    public void setUserDao(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    public void saveUser(User user){
        this.userDAO.saveUser(user);
    }
}

测试一下

BeanFactory appContext = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) appContext.getBean("userService");
userService.saveUser(new User());

输出saving user,即成功调用了UserDAOImpl中的save方法

上边的代码有一个限制就是beans.xml中一个类只能配置一个bean,比如beans.xml配置成如下这样时就会报错

<?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:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>
    <bean id="userDao" class="ml.orlion.dao.impl.UserDAOImpl">
    </bean>
    
    <bean id="userDao1" class="ml.orlion.dao.impl.UserDAOImpl">
    </bean>
    
    <bean id="userService" class="ml.orlion.service.UserService">
    </bean>
</beans>

这时候可以把UserService类改成如下(在setUserService方法中加注解)

package ml.orlion.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import ml.orlion.dao.UserDAO;
import ml.orlion.dao.impl.UserDAOImpl;
import ml.orlion.model.User; public class UserService {     private UserDAO userDAO = new UserDAOImpl();     public UserDAO getUserDao() {
        
        return userDAO;
    }
    @Autowired
    public void setUserDao(@Qualifier("userDao") UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    public void saveUser(User user){
        this.userDAO.saveUser(user);
    }
}

这时候再运行就不会报错了。

二、@Reosource

从bean容器中注入bean,默认是按名字查找,找不到再按类型,可以指定名字

beans.xml中配置

<?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:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>
   
<bean id="userDao" class="ml.orlion.dao.impl.UserDAOImpl">
</bean> <bean id="userDao1" class="ml.orlion.dao.impl.UserDAOImpl">
</bean> <bean id="userService" class="ml.orlion.service.UserService">
</bean>
</beans>

UserService.java:

package ml.orlion.service;

import javax.annotation.Resource;

import ml.orlion.dao.UserDAO;
import ml.orlion.dao.impl.UserDAOImpl;
import ml.orlion.model.User; public class UserService { private UserDAO userDAO = new UserDAOImpl(); public UserDAO getUserDao() { return userDAO;
}
@Resource(name="userDao")
public void setUserDao(UserDAO userDAO) {
this.userDAO = userDAO;
} public void saveUser(User user){
this.userDAO.saveUser(user);
}
}

测试可以运行会输出saving user

三、@Component

将一个类声明为spring的bean

beans.xml

<?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:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>
   <context:component-scan base-package="ml.orlion"></context:component-scan>
   
</beans>

其中<context:component-scan base-package="ml.orlion"></context:component-scan>表示从包名为ml.orlion下的所有类中找Component.

UserDAOImpl.java

package ml.orlion.dao.impl;

import org.springframework.stereotype.Component;

import ml.orlion.dao.UserDAO;
import ml.orlion.model.User;
@Component("userDao") //默认名字是userDaoImpl
public class UserDAOImpl implements UserDAO{ public void saveUser(User user){
System.out.println("save usering");
}
}

UserService.java

package ml.orlion.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import ml.orlion.dao.UserDAO;
import ml.orlion.dao.impl.UserDAOImpl;
import ml.orlion.model.User;
@Component("userService")
public class UserService { private UserDAO userDAO = new UserDAOImpl(); public UserDAO getUserDao() { return userDAO;
}
@Resource(name="userDao")
public void setUserDao(UserDAO userDAO) {
this.userDAO = userDAO;
} public void saveUser(User user){
this.userDAO.saveUser(user);
}
}

测试一下:

BeanFactory appContext = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) appContext.getBean("userService");
userService.saveUser(new User());

运行会输出saving user

四、@Scope、@PostConstruct、@PreDestroy

可以在类定义之前添加注释@Scope("prototype")将bean声明为每次调用时都重新new一个。

@PostConstructbean声明在初始化时运行的方法

@PreDestroy声明在销毁时运行的方法

Spring(四)注解配置Ioc的更多相关文章

  1. java框架之Spring(2)-注解配置IOC&AOP配置

    注解配置IoC 准备 1.要使用注解方式配置 IoC,除了之前引入的基础 jar 包,还需要引入 spring-aop 支持包,如下: 2.在 applicationContext.xml 中引入 c ...

  2. JavaWeb_(Spring框架)注解配置

    系列博文 JavaWeb_(Spring框架)xml配置文件  传送门 JavaWeb_(Spring框架)注解配置 传送门 Spring注解配置 a)导包和约束:基本包.aop包+context约束 ...

  3. Spring详解(四)------注解配置IOC、DI

    Annotation(注解)是JDK1.5及以后版本引入的.它可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时检查.注解是以‘@注解名’在代码中存在的. 前面讲解 IOC 和 DI 都是通过 ...

  4. Spring自定义注解配置切面实现日志记录

    一: spring-mvc.xml: <!--配置日志切面 start,必须与mvc配置在同一个配置文件,否则无法切入Controller层--><!-- 声明自动为spring容器 ...

  5. spring基于注解的IoC以及IoC的案例

    1.Spring中IoC的常用注解 1.1明确: (1)基于注解的配置和xml的配置要实现的功能都是一样的,都是要降低程序之间的耦合,只是配置的形式不一样 2.案例:使用xml方式和注解方式实现单表的 ...

  6. spring aop注解配置

    spring aop是面向切面编程,使用了动态代理的技术,这样可以使业务逻辑的代码不掺入其他乱七八糟的代码 可以在切面上实现合法性校验.权限检验.日志记录... spring aop 用的多的有两种配 ...

  7. Spring的注解配置与XML配置之间的比较

    注释配置相对于 XML 配置具有很多的优势: 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作. 如:使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO ...

  8. Spring纯注解配置

    待改造的问题 我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置: <!-- 告知spring框架在,读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器 ...

  9. Spring详解(二)------注解配置IOC

    @Configuration:告诉Spring这是一个配置类 @Bean("person")-->作用于方法:给容器中注册一个Bean;类型为返回值的类型 @Componen ...

随机推荐

  1. bzoj 3507: [Cqoi2014]通配符匹配

    Description 几乎所有操作系统的命令行界面(CLI)中都支持文件名的通配符匹配以方便用户.最常见的通配符有两个,一个是星号(“”’),可以匹配0个及以上的任意字符:另一个是问号(“?”),可 ...

  2. python基础01 Hello World!

    摘要:简单的Hello Word! python 命令行 如已经安装python,那么在linux命令行中输入 $python 将进入python.乱吼在命令行提示符>>>后面输入 ...

  3. rpm 看 rpm 包内容

    1.命令 rpm #rpm -qpl packetname

  4. C#SerialPort如何读取串口数据并显示在TextBox上

    SerialPort中串口数据的读取与写入有较大的不同.由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取.一.线程实时读串口:二.事件触发方式实现. 由于线程实时读串口的效率不是十分高 ...

  5. Mysql 表分区

    是否支持分区:mysql> show variables like '%partition%';+-----------------------+-------+| Variable_name ...

  6. 部署Thomas Kyte 的 runstats 工具

    runstats是由Thomas Kyte开发的脚本,该脚本能对做同一件事的两个不同方法进行比较,得出孰优孰劣的结果. 1.授权 SQL> grant select on v_$statname ...

  7. C# 开源组件--Word操作组件DocX

    使用模版生成简历 读写表格数据 合并单元格 工具源代码下载 学习使用 使用模版生成简历 下面将以一个简历实例来讲解DocX对表格的操作,先看看生成的效果 private static void Cre ...

  8. adb devices出现no permissions

    在做Android开发的时候,有些设备插入USB调试线,无法调试,出现以下错误: joey 09:58 $ adb devices List of devices attached 20080411 ...

  9. Python读写文件

    Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('t ...

  10. 转:隐马尔可夫模型(HMM)攻略

    隐马尔可夫模型 (Hidden Markov Model,HMM) 最初由 L. E. Baum 和其它一些学者发表在一系列的统计学论文中,随后在语言识别,自然语言处理以及生物信息等领域体现了很大的价 ...