您的位置:首页 > 编程语言 > Java开发

J2EE进阶学习——Spring框架(四):Spring的bean管理(注解)

2018-03-08 18:29 441 查看
Spring注解的准备工作

1.导入包

2.创建类,创建方法

3.创建Spring配置文件,引入约束

第一天做IOC基本功能,引入约束beans

做Spring的IOC注解开发,引入新的约束

<?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 -->

</beans>


附上文档网站:https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html

4.开启注解扫描

<!-- 开启注解扫描
1.到包里面扫描类、方法、属性上面是否有注解
2.base-package:这是被扫描的包
-->
<context:component-scan base-package="com.TiHom"></context:component-scan>


1.使用注解创建对象

在创建对象的类上面使用注解实现

创建对象有四个注解

@Component:组件

@Controller:web层

@Service:业务层

@Repository:持久层

目前这四个注解功能是一样的,都用来创建对象

创建对象单实例还是多实例

2.使用注解注入属性

创建service类,创建dao类,在service得到dao对象

注入属性第一个注解 @AutoWired

创建dao和service对象

@Component(value="userDao")
public class UserDao{

@Service(value="userService")
public class UserService{


在service类里面定义dao类型属性

注入属性的第二个注解 @Resource

@Resource(name="userDao")
private UserDao userDao;


3.xml和注解方式混合使用

在配置文件中配置对象

在注解中配置属性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐