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

Spring框架bean的注解管理方法之一 使用注解生成对象

2018-01-01 00:41 453 查看
首先在原有的jar包:需Spring压缩包中的四个核心JAR包beans 、context、core 和expression下载地址:
https://pan.baidu.com/s/1qXLHzAW
以及日志jar包commons-logging 和log4j下载地址:
https://pan.baidu.com/s/1mimTW5i
再增加一个spring-aop-5.0.1.RELEASE.jar增加注解功能的jar包名字是aop有些奇怪(不是annotation ,也不是context)  然后,src中建立一个xml配置文件,增加新的context的约束语句,如下:
<?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">
<!--  开启注解扫描  -->
<context:component-scan base-package="com.swift"></context:component-scan>
</beans>
注解的方法xml中配置对象及属性只用这一句<context:component-scan base-package="com.swift"></context:component-scan>即可,com.swift是包名,最好写上一级,可以扫描到里边所有的包下边使用注解来创建对象:
package com.swift.user;

import org.springframework.stereotype.Component;

@Component(value="user")
public class User {
public String fun() {
return "The User's fun()..........";
}
}
 

注解创建对象@Component(value="user")相当于之前在xml配置文件中使用<bean id="user" class="com.swift.User"></bean>实际上除了可以用@Component 还可以用@Service @Controller @Repository ,功效一样,是预备不同层使用的默认单实例,那么如果要创建多对象可以这样写@Component(value="user")@Scope(value="prototype")value的值不写或者写singleton都是单实例关于value="prototype" 还有待补充     

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