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

首先在原有的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" 还有待补充


 

 

 

 

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值