关于bean:Spring中用注解创建bean实例

4次阅读

共计 699 个字符,预计需要花费 2 分钟才能阅读完成。

Spring 中提供以下注解来创立 bean 实例:
1)@Component
2)@Service
3)@Controller
4)@Repository
以上 4 个注解的性能是一样的,都能够用来创立 bean 实例

步骤:
1)引入 spring-aop 依赖包
2)开启注解扫描,开启后才会去扫描哪个目录下应用了注解

<context:component-scan base-package="com.zong.spring,com.zong.bean"></context:component-scan>

应用过滤器,指定扫描文件

<context:component-scan base-package="com.zong.spring,com.zong.bean" use-default-filters="false">
  // 只扫描 Controller 注解
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  // 不扫描 Controller 注解
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

3) 在类下面增加注解

@Component(value="userService")
public class UserService{}

value 中的值等于 bean.xml 文件中的 id 属性,默认是类名且首字母小写

正文完
 0