spring5入门(九):基于注解管理bean,创建对象
- 注解简介
注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)
使用注解,注解作用在类上面,方法上面,属性上面
使用注解目的:简化 xml 配置
- 有关bean的注解
@Component
@Service
@Controller
@Repository
-
使用注解创建对象
-
添加依赖
-
开启组件扫描
<?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.ychen"></context:component-scan>
</beans>
创建bean,如果不指定value,默认时类名的首字母小写
@Component(value = "userService")
public class UserService {
public void add() {
System.out.println("service add.......");
}
}
- 测试方法
public class Test3 {
@Test
public void testAdd() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
- 控制台
com.ychen.spring.ser.UserService@452e19ca
service add.......
Process finished with exit code 0
组件扫描详情
<!-- 表示不扫描所有组件,只扫描带Controller注解的类 -->
<context:component-scan base-package="com.atguigu" use-defaultfilters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 表示除了带Controller注解的类都扫描 -->
<context:component-scan base-package="com.atguigu">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>