IOC操作Bean管理(基于注解方式)

注解

注解:

  • 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值)。
  • 使用注解,注解作用再类上面,方法上面,属性上面。
  • 使用注解目的:简化XML配置。

使用注解创建对象

1.Component:作用把当前类对象存到Spring容器中。属性value,用于指定bean的id,如果不写默认当前类名首字母小写。
2.Controller:一般用于表现层。
3.Service:一般用于业务层
4.Repository:一般用在持久层。

例子:使用注解创建一个对象。
开始组件扫描:XML文件头部需要声明:

 xmlns:context="http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

使用context标签:

 <context:component-scan base-package="com.gz.pojo"></context:component-scan>

使用注解创建对象:

@Component(value = "human")
public class Human {
    public void test(){
        System.out.println("创建对象使用测试方法");
    }
}

测试:

 @Test
    public void test1(){

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        Human human = context.getBean("human", Human.class);
        human.test();
    }

组件扫描细节配置

context标签属性: use-default-filters 可以自己配置filter去扫描内容。默认值为true。
include-filter:表示你扫描的注解创建对象

 <context:component-scan base-package="com.gz" use-default-filters="false">
 		<!--表示只扫描Repository创建对象-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
   </context:component-scan>

exclude-filter:表示你过滤的注解,没有创建对象

<context:component-scan base-package="com.gz" use-default-filters="false">
       <!--表示不扫描Repository创建对象-->
       <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
   </context:component-scan>

使用注解注入属性

1.Autowried:自动按照类型注入,只要IOC容器中又唯一的bean对象和注入变量类型匹配,就可以注入成功。如果IOC容器中没有任何bean类型和要注入的变量类型匹配,则报错。
2.Qualifier:再按照类中注入的基础上再按照名称注入,在给类成员注入时,不能单独使用,在给方法注入时可以,属性value用于指定bean的id。
3.Resource:直接按照bean的id注入,可以单独使用。属性value用于指定bean的id。
4.value:用于注入基本类型和String类型的数据。

注意:前三种不能注入基本类型和String类型的数据,集合类型的注入只能通过XML实现

完全注解开发

(1)创建配置类,替代 xml 配置文件

//作为配置文件,替代xml配置文件
@Configuration
//扫描内容
@ComponentScan(basePackages = {"com.gz.pojo"})
public class Human {
    public void test(){
        System.out.println("创建对象使用测试方法");
    }
}

测试类:

public class TextDemo {
    @Test
    public void test1(){
//加载配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Human.class);
        Human human = context.getBean("human", Human.class);
        human.test();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值