博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring中注解的使用
阅读量:2440 次
发布时间:2019-05-10

本文共 5757 字,大约阅读时间需要 19 分钟。

Spring中如何使用注解定义Bean?

 除了@Component外,Spring提供了3个功能基本和@Component等效的注解 :

@Repository 用于对DAO实现类进行标注

@Service 用于对Service实现类进行标注 @Controller

用于对Controller实现类进行标注

 注意:这三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强

Bean的属性注入:(使用注解方式)

*普通属性注入:

@Value(value="success")

private String info;

*对象属性注入:

方法一:

@Autowired:自动装配默认使用类型注入。

方法二:

@Autowired(required=true)  //通过@Autowired的required属性,设置一定要找 到匹配的Bean

@Qualifier("userDao") //按名称注入,在加上@Qualifier("userDao")

private UserDao userDao;

方法3:

Spring提供对JSR-250中定义@Resource标准注解的支持 @Resource和@Autowired注解功能相似

@Resource(name="userDao") //使用名称注入,等效于@Autowired使用名称注入

private UserDao userDao;

配置Bean初始化方法和销毁方法:

初始化方法:在方法前加@PostConstruct   执行初始化方法

销毁方法:在方法前加@PreDestroy  执行销毁方法

注意:使用注解配置的Bean和xml配置的<bean>配置的一样,默认作用范围都是singleton

 使用注解配置Bean的作用范围:

@Scope  默认代表单例

@Scope(value="prototype")  代表多例

下面是一个实例,描述了如何使用注解的方式配置Bean;

实例1:编写一个类UserService,然后在编写一个Proudct类用于对象属性注入,代码如下:

package com.study.Demo1;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.stereotype.Component;@Component("userService")public class UserService {	@Value("小龙")	private String name;		@Autowired	private  Product product;//使用默认类型注入	//	@Autowired(required=true) //值为true代表遇到异常就抛出异常,为false的话,遇到异常也继续执行下去//	@Qualifier("product")	//按名称注入,和上面的单独使用@Autowired效果一样//	@Resource(name="product")	//这一条代码等价于上面两条代码//	private  Product product;	public void show() {		System.out.println("你好啊!"+name);	}	@Override	public String toString() {		return "UserService [name=" + name + ", product=" + product + "]";	}		}

 编写Product类,用于对象属性注入;代码如下:

package com.study.Demo1;import org.springframework.stereotype.Component;import org.springframework.stereotype.Repository;//或者换成@Repository//@Repository("product")@Component("product")public class Product {}

最后编写一个测试类,用于实例1的测试;代码如下:

 

package com.study.Demo1;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {		@Test	public void Test1() {		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");		UserService userService = (UserService) applicationContext.getBean("userService");		//userService.show();		System.out.println(userService);	}}

Spring3.0提供使用Java类提供Bean定义信息(使用较少)

*@Configuration 指定POJO类为Spring提供Bean定义信息

*@Bean 提供一个Bean定义信息

实例2:编写两个javaBean类,分别为Car类,Product类,分别定义了name,price属性,并且提供setter()方法,代码如下:

package com.study.spring3.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 com.study.spring3.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 + "]";	}	}

然后编写一个配置信息类BeanConfig,用于返回Car类的对象,以及Product类的对象。代码如下:

package com.study.spring3.demo2;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * 类的配置信息 * @author 哎呦不错呦 * */@Configurationpublic class BeanConfig {		@Bean(name="car")	public Car showCar() {		Car car = new Car();		car.setName("宝马");		car.setPrice(500000d);		return car;	}		@Bean(name="product")	public Product showProduct() {		Product product = new Product();		product.setName("小米8");		product.setPrice(3000d);		return product;	}}

最后编写一个测试类SpringTest2,用于测试是否获取了Bean对象;

package com.study.spring3.demo2;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest2 {	@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);	}}

编写实例1,实例2的配置文件applicationContext.xml文件,代码如下:

传统XML配置和注解配置混合使用:

 下面举一个例子:用于传统XML配置和注解配置混合使用的方法;

实例3:创建3个类,CustomerDao类,Order类,CustomerService类,其中在CustomerService类中提供CustomerDao类,Order类这两个类对象的属性;下面是代码实例:

package com.study.spring3.demo3;public class CustomerDao {}package com.study.spring3.demo3;public class OrderDao {}package com.study.spring3.demo3;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;public class CustomerService {	private CustomerDao customerDao;	@Autowired	@Qualifier("orderDao")	//注解作用在属性上可以没有setter方法	private OrderDao orderDao;	public void setCustomerDao(CustomerDao customerDao) {		this.customerDao = customerDao;	}		@Override	public String toString() {		return "CustomerService [customerDao=" + customerDao + ", orderDao=" + orderDao + "]";	}	}

然后编写ApplicationContext.xml的代码,代码如下:

最后编写测试类SpringTest3的代码,用于实例3的测试,代码如下:

package com.study.spring3.demo3;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest3 {	@Test	public void demo1() {		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml");		CustomerService customerService = (CustomerService) applicationContext.getBean("customerService");		System.out.println(customerService);	}}

参考:传智播客   www.itcast.com

转载地址:http://izdqb.baihongyu.com/

你可能感兴趣的文章
Tomcat Server组成
查看>>
Java 使用Token令牌防止表单重复提交
查看>>
Tomcat 部署war文件
查看>>
桌面文件删除不掉的解决方案
查看>>
MyEclipse10.x 安装 properties editor插件,properties文件显示中文
查看>>
Json学习一(基础概念知识学习)
查看>>
Font "楷体_GB2312" is not available to the JVM. See the Javadoc for more det
查看>>
mysql5.7.11服务无法启动,错误代码3534
查看>>
Mysql5.7.11解压版在windows10上的安装配置
查看>>
mysql5.7.11修改root密码
查看>>
navicate Premium注册码
查看>>
MySQL 执行插入操作时报1366 - Incorrect string value: '\xE4\xB8\xAD\xE6\x96\x87' for column 'name' at row 1
查看>>
jsp文件放在WebRoot下还是WebInfo下
查看>>
java.util.ConcurrentModificationException at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(L
查看>>
java.lang.IllegalStateException: Cannot forward after response has been committed
查看>>
java Swing JTable 隐藏某列
查看>>
Jtextarea与Jtable中下拉框始终显示在最后一行
查看>>
jtable中某列实现html中a标签效果,鼠标移到上面去的时候显示手型效果
查看>>
'@P0'附近有语法错误
查看>>
String、StringBuilder、StringBuffer的区别
查看>>