spring----通过注解配置bean----笔记

标注了是笔记,因为初学javaweb的框架还不熟悉体系,如有记录错误实属正常。

目录结构
在这里插入图片描述

各个在top.demo.com的类 和子包的类 都是拿来测试 的bean且使用的注解都如包的最后单词标识。只发一个类代码

package top.demo.com;

import org.springframework.stereotype.Component;

@Component
public class MyComponent {

	public String name="MyComponent";

	@Override
	public String toString() {
		return "MyComponent [name=" + name + "]";
	}
}

测试和笔记

package top.demo.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import top.demo.com.MyComponent;
import top.demo.com.repository.Dao;
import top.demo.com.service.ActiveService;

public class Main {

	public static void main(String argv[]) {
		
		ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
		
		
		/**
		 * 报错:在使用注解的方式配置bean 的时候报错 没有找到类 org/springframework/aop/TargetSource
		 * 原因 :除了spring下的 core beans context expression包还需要倒入aop的包 
		 * 
		 * 注意:bean 的获取方式 ,名字如果没有在注解的value属性指定的时候,默认是类名第一个字母小写
		 * 
		 *  @Component、@Repository、@Service 和 @Controller
		 * 
		 * 
		 * context:exclude-filter  type="annotation"的用法
		 * expression 后跟的是注解的全类名如org.springframework.stereotype.Repository
		 * 而不是你的bean的全类名
		 * 
		 * 其次 我测试  在基包下一个类定义了某个注解假设为@Component,然后exclude-filter type="annotation"
		 * 排除使用这个@Component的类  那么子包下的类也会报错找不到 
		 * 
		 * 测试 在基包下单独一个类比较特殊 除了上述 还有:
		 * 
		 * <context:component-scan base-package="top.demo.com" use-default-filters="false" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
			use-default-filters="false"关闭了默认的过滤器
		 * 理想应该只扫描Component注解的类 但是这个类在基包 下面子包下的其他注解的类也可以获取到 
		 * 
		 * 在此推断出 spring的扫描不是完全扫描 是符合到条件了就终止了扫描 且在这个条件成立情况下 子包内的也默认都成立了
		 * 
		 * 
		 * */
		MyComponent com=(MyComponent) app.getBean("myComponent");
		System.out.println(com);
		
		Dao dao=(Dao) app.getBean("dao");
		System.out.println(dao);
		
		
		ActiveService activeService=(ActiveService) app.getBean("activeService");
		System.out.println(activeService);
		
		
	}
	
}

配置文件

<?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-4.3.xsd">


<context:component-scan base-package="top.demo.com" use-default-filters="false" >


<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>

</context:component-scan>

</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值