IOC装配Bean(注解方式)(5)

Spring的注解装配Bean

Spring2.5 引入使用注解去定义Bean
@Component  描述Spring框架中Bean
Spring的框架中提供了与@Component注解等效的三个注解:
@Repository 用于对DAO实现类进行标注
@Service 用于对Service实现类进行标注
@Controller 用于对Controller实现类进行标注
***** 三个注解为了后续版本进行增强的.

Bean的属性注入:

普通属性;
@Value(value="itcast")
    private String info;

对象属性:
@Autowired:自动装配默认使用类型注入.
@Autowired
@Qualifier("userDao")       --- 按名称进行注入.

@Autowired
@Qualifier("userDao")
private UserDao userDao;
等价于
@Resource(name="userDao")
private UserDao userDao;

Bean其他的属性的配置:

配置Bean初始化方法和销毁方法:
* init-method 和 destroy-method.
@PostConstruct 初始化
@PreDestroy  销毁

配置Bean的作用范围:
@Scope

以下是测试案例:

<!-- 扫描多个目录方法两种
    第一种:<context:component-scan base-package="cn.spring.demo1,cn.spring.demo2" />
    第二种:<context:component-scan base-package="cn.spring" />
-->
    <context:component-scan base-package="cn.spring" />

UserService.java

package cn.spring.demo1;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/*
 * 注解的方式装配bean
 */
//在spring配置文件中<bean id="userservice" class="cn.spring.demo1.UserService">
//@Component("userservice")
@Service("userservice")
//scope默认是单实例
@Scope(value="prototype")
public class UserService {
    @Value(value="测试1")
    private String info;
    //按类型注入的话@Autowired(required=false 忽略异常)
    //@Autowired(required=true)
    //按名称注入的话加@Qualifier("userdaoonly") 要跟userdao里面的@Repository("userdaoonly")一样(第二种)
    //@Qualifier("userdaoonly")
    //@[email protected][email protected]("userdaoonly")
    @Resource(name="userdaoonly")
    private UserDao userdao;

    public void sayHello(){
        System.out.println("Hello spring Annotation..."+info+userdao);
    }

/*  @Override
    public String toString() {
        return "UserService [info=" + info + ", userdao=" + userdao + "]";
    }*/

    @PostConstruct
    public void setup(){
        System.out.println("初始化……");
    }

    @PreDestroy
    public void teardwon(){
        System.out.println("销毁……");
    }
}

--------------------------------------------------------------------------------------------------------------------------------------------

UserDao.java
package cn.spring.demo1;

import org.springframework.stereotype.Repository;

@Repository("userdaoonly")
public class UserDao {

}
-------------------------------------------------------------------------------------------------------------------------------------
package cn.spring.demo1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//注解的方式
public class SpringTest1 {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        UserService userservice = (UserService) applicationcontext
                .getBean("userservice");
        //      userservice.sayHello();
        System.out.println(userservice);
        UserService userservice2 = (UserService) applicationcontext
        .getBean("userservice");
        //userservice.sayHello();
        System.out.println(userservice2);
        applicationcontext.close();
    }
}

Spring3.0提供使用Java类定义Bean信息的方法

@Configuration
public class BeanConfig {

    @Bean(name="car")
    public Car showCar(){
        Car car = new Car();
        car.setName("长安");
        car.setPrice(40000d);
        return car;
    }

    @Bean(name="product")
    public Product initProduct(){
        Product product = new Product();
        product.setName("空调");
        product.setPrice(3000d);
        return product;
    }
}


以下是测试案例:

//这个是java类定义bean信息的方式;
package cn.spring.demo2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

    @Bean(name="car")
    public Car showCar() {
        Car car = new Car();
        car.setName("长安");
        car.setPrice(123.00);
        return car;
    }

    @Bean(name="product")
    public Product showProduct() {
        Product product = new Product();
        product.setName("空调");
        product.setPrice(1234.00);
        return product;
    }
}
-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

public class Car {
    private String name;
    private Double price;

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }

}

-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

public class Product {
    private String name;
    private Double price;

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + "]";
    }

}

-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.spring.demo1.UserService;

public class SpringTest {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        Car car = (Car) applicationcontext
                .getBean("car");
        Product product = (Product) applicationcontext
                .getBean("product");

        System.out.println(car);
        System.out.println(product);
    }
}

实际开发中使用XML还是注解?

XML:
* bean管理
注解;
* 注入属性的时候比较方便.

两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入.

<context:annotation-config/>
@Autowired
@Qualifier("orderDao")
private OrderDao orderDao;

最后一个整合一下,一个使用XML注册bean一个用注释bean

    <context:annotation-config/>

    <bean id="customerdao" class="cn.spring.demo3.CustomerDao"></bean>

      <bean id="orderdao" class="cn.spring.demo3.OrderDao"></bean>

    <bean id="customerservice" class="cn.spring.demo3.CustomerService">
        <property name="customerdao" ref="customerdao"></property>
        <!--  <property name="orderdao" ref="orderdao"></property>-->
    </bean>
package cn.spring.demo3;

public class CustomerDao {

}
-------------------------------------------
package cn.spring.demo3;

public class OrderDao {

}
--------------------------------------------
package cn.spring.demo3;

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

public class CustomerService {

    private CustomerDao customerdao;

    @Autowired
    @Qualifier("orderdao")
    private OrderDao orderdao;

    public void setCustomerdao(CustomerDao customerdao) {
        this.customerdao = customerdao;
    }

    @Override
    public String toString() {
        return "CustomerService [customerdao=" + customerdao + ", orderdao="
                + orderdao + "]";
    }
}
-----------------------------------------------
测试类写法
package cn.spring.demo3;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext2.xml");

        CustomerService customerservice = (CustomerService) applicationcontext
                .getBean("customerservice");
        System.out.println(customerservice);
    }

}

原文地址:http://blog.51cto.com/4534309/2107862

时间: 2024-08-09 21:52:06

IOC装配Bean(注解方式)(5)的相关文章

05_IOC容器装配Bean(注解方式)

IOC容器装配Bean(注解方式) 1.使用注解方式进行Bean注册 xml 方式: <bean id="" class=""> spring2.5版本 提供一组注解,完成Bean注册 * @Component 描述Spring框架中Bean 导入jar 和 xml方式开发是相同的 第一步 编写Class,在声明上 添加 @Component /** * 使用Spring2.5注解 注册Bean */ @Component("helloServ

04_IOC容器装配Bean(xml方式)

IOC容器装配Bean(xml方式) 1.Spring 提供配置Bean三种实例化方式 1)使用类构造器实例化(默认无参数) <bean id="bean1" class="cn.itcast.spring.b_instance.Bean1"></bean> 2)使用静态工厂方法实例化(简单工厂模式) //下面这段配置的含义:调用Bean2Factory的getBean2方法得到bean2 <bean id="bean2&qu

Spring框架---IOC装配Bean

IOC装配Bean (1)Spring框架Bean实例化的方式提供了三种方式实例化Bean 构造方法实例化(默认无参数,用的最多) 静态工厂实例化 实例工厂实例化 下面先写这三种方法的applicationContext.xml配置文件: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans&

spring实战之Bean的自动装配(非注解方式)

Bean的自动装配 自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bean的依赖关系. 1.1 自动装配Bean属性: Spring提供了四种各具特色的自动装配策略: 1.byName-把与Bean的属性具有相同名字的其他Bean自动装配到Bean的对应属性中.如果没有跟属性的名字相匹配的Bean,则该属性不进行装配. 2.byType-把与Bean的属性具有相同类型的其他Bea

使用 properties 配置文件装配 bean 的方式

在spring中将bean 注册到spring 容器中常见的有三种方式(两类): 先说明配置文件内容:application.yml,有一段配置如下 persons: youtube: name: youtube age: 18 google: name: google age: 20 第一类:将单个类注册到容器中 第一种,使用 @ConfigurationProperties + @Component,配置 GoogleUser @Configuration //效果等同于 @Componen

IOC装配Bean

Spring框架Bean实例化的方式 提供了三种方式实例化Bean 构造方法实例化(默认无参数,用的最多) 静态工厂实例化 实例工厂实例化 无参数构造方法的实例化 <!-- 默认情况下使用的就是无参数的构造方法. --> <bean id="bean1" class="cn.yzu.spring3.demo2.Bean1"></bean> 静态工厂实例化 public class Bean2Factory { public sta

IOC装配Bean(2)

Spring框架Bean实例化的方式 提供了三种方式实例化Bean. * 构造方法实例化:(默认无参数) * 静态工厂实例化: * 实例工厂实例化: 无参数构造方法的实例化 <!-- 默认情况下使用的就是无参数的构造方法. --> <bean id="bean1" class="cn.spring.demo2.Bean1"></bean> package cn.spring.demo2; /* * 使用无参数的构造方法实例化 */

工作中遇到的问题--缓存配置(使用@Configuration装配 @Bean的方式注入)

@EnableCaching@Configurationpublic class MFGCachingConfiguration { @Autowired private MFGSettings mfgSettings; @Bean(name="MFGKeyGenerator") public KeyGenerator MFGKeyGenerator(){ SimpleKeyGenerator defaultKeyGen = new SimpleKeyGenerator(); KeyG

JAVAWEB开发之Spring详解之——Spring的入门以及IOC容器装配Bean(xml和注解的方式)、Spring整合web开发、整合Junit4测试

Spring框架学习路线 Spring的IOC Spring的AOP,AspectJ Spring的事务管理,三大框架的整合 Spring框架概述 什么是Spring? Spring是分层的JavaSE/EE full-stack(一站式)轻量级开源框架. 所谓分层: SUN提供的EE的三层结构:web层.业务层.数据访问层(也称持久层,集成层). Struts2是web层基于MVC设计模式框架. Hibernate是持久的一个ORM的框架. 所谓一站式:Spring框架有对三层的每层解决方案.