IOC操作Bean管理(基于注解方式)
一、 IOC操作Bean管理(基于注解方式)
1. 注解相关概念
- 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)
- 使用注解,注解可以作用在类,方法,属性上面
- 目的:简化xml配置
2. Spring针对Bean管理中创建对象提供对象
- @Conponent
- @Service
- @Controller
- @Repository
上面四个注解功能是一样的,都可用来创建bean实例
3. 基于注解方式创建对象
-
开启组件扫描
- 如果扫描多个包,多个包使用逗号隔开
- 扫描包上层目录
<context:component-scan base-package="com.zyy.spring_demo"></context:component-scan> -
创建类,在类上面添加创建对象注解
//注解里,value属性值可以省略不写 //默认值是类名称,其首字母小写 @Component(value = "person") public class Person { public void add(){ System.out.println("Add............."); } }
4. 开启组件扫描细节配置
<!-- 示例1-->
<!-- use-default-filters="false", 表示不使用默认filter,自己配置filter-->
<!-- context:include-filter, 设置扫描内容-->
<!-- 扫描带有注解Controller的类-->
<context:component-scan base-package="com.zyy.spring_demo" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 示例2-->
<!-- 扫描下面配置包中所有内容-->
<!-- exclude-filter, 设置那些包不扫描-->
<context:component-scan base-package="com.zyy.spring_demo">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
5. 基于注解方式实现属性注入
1. @Autowired
- 根据属性类性进行自动装配
-
把service和dao对象创建,在service和dao类添加创建对象
-
在service注入dao对象,在service类添加dao类型属性,在属性上面使用注解
@Service public class Person { @Autowired private PersonDao personDao; public void add(){ System.out.println("Add............."); personDao.add(); } }
2. @Qualifier
-
根据属性名称进行注入
-
该注解的使用,要和上面@Autowired一起使用
@Service public class Person { @Autowired // 同一类型的多个类,按名称查找 @Qualifier(value = "personDaoImpl1") private PersonDao personDao; public void add(){ System.out.println("Add............."); personDao.add(); } }
3. Resource
- 可以根据类型注入,可以根据名称注入
- 代码参考上方两个
4. Value
-
注入普通类型属性
@Service public class Person { @Value(value="abc") private String name; public void add(){ System.out.println(name); } }
6. 完全注解开发
-
创建配置类,替代xml配置文件
@Configuration @ComponentScan(basePackages = {"com.zyy.spring_demo"}) public class SpringConfig { } -
编写测试类
@Test public void test2(){ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); Person person = context.getBean("person", Person.class); person.add(); }

浙公网安备 33010602011771号