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是根据类名找到对应的类