spring bean的注解开发

1.注解开发准备工作

(1)导入spring最基本的jar包

地址:http://download.csdn.net/detail/m0_37983376/9880715

(2)导入aop的jar包

(3)创建类,并给出方法

package com.sq.service;
/**
 *@author sq
 *
 */
public class UserService {
	
	public void add(){
		System.out.println("add...");
	}
}
(4)创建配置文件,引入约束



(5)开启注解的扫描

<?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"> <!-- bean definitions here -->
	<!-- 开启注解扫描
		(1)到包里面扫描类,方法,属性上面是否有注解
	 -->
	<context:component-scan base-package="com.sq.service"></context:component-scan>
	
	
	<!-- 
		只会扫描属性上面的注解
	 -->
	<context:annotation-config></context:annotation-config>
</beans>


2.注解创建对象

(1)在需要创建的对象类上面添加注解

@Component(value="userService")
public class UserService {
(2)创建对象有四个注解

-- @Component

-- @Controller web层

-- @Service 业务层

-- @Repository 持久层

(3)创建对象单实例还是多实例

@Component(value="userService")
@Scope(value="prototype")
public class UserService {


3.注解注入属性

(1)创建dao和service类

package com.sq.service;

import org.springframework.stereotype.Component;

/**
 *@author sq
 *
 */

@Component
public class UserDao {

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

package com.sq.service;


import javax.annotation.Resource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


/**
 *@author sq
 *
 */


@Component(value="userService")
public class UserService {
	//得到dao对象
	//1定义dao类型属性
	//在dao属性上面使用注解完成对象注入
//	@Autowired
	@Resource(name="userDao")
	private UserDao userDao;
	//使用注解不需要set方法
	
	public void add(){
		System.out.println("add...");
		userDao.dao();
	}
}

注意:autowired是根据类名找到对应的类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值