相应的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"> <!-- bean definitions here -->
<!-- 开启注解扫描
(1)到包里面扫描类、方法、属性上面是否有注解
-->
<context:component-scan base-package="cn.itcast"></context:component-scan>
<!-- 只扫描属性上的注解 -->
<!-- <context:annotation-config ></context:annotation-config> -->
</beans>
相关的注解方法展示
类的注解有四种分别是:@Component @Service @Controller @Repository
@Scope(value="prototype" ) 是对单例多例范围的注解
属性的注解有两种分别是:
@Autowired 通过属性类型自动关联相关的类
@Resource(name=“ 相对应的类的注解value值”) 人为指定更加精准;
package cn.itcast.anno;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service(value="userService")
//@Component,@Service,@Controller,@Repository是对类的注解
//value的值相当于xml配置文件中bean的id
@Scope(value="singleton")
//@Scope是对类的单例多例范围进行注解
public class UserService {
//得到dao对象
//1、定义dao类型属性
//2在dao属性上使用注解,完成对象注入
//@Autowired
//自动关联注解,通过对属性的类名找到属性对象,与UserDao的注解名无关
@Resource(name="userDao")
//name属性值为注解UserDao类的名value值userDao
private UserDao userDao;
//使用注解方法不需要手动生成setter方法
public void add() {
System.out.println("service.............");
userDao.add();
}
}
本文详细介绍了Spring框架中使用XML和注解的方式进行Bean的配置。重点讲解了@Component、@Service、@Controller、@Repository等类注解以及@Autowired、@Resource等属性注解的应用,并展示了如何通过<context:component-scan>进行注解扫描。
2776

被折叠的 条评论
为什么被折叠?



