Spring学习-03课SpringIoC的注解使用-将一个类通过注解的方式注册为Bean

108 阅读2分钟

1、spring config xml 文件中 设置自动扫描 和 扫描路径

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

2、对应的类上标注 注解

@Contorller 标记在控制层的类注册为Bean组件

@Service 标记在业务层的类注册为Bean组件

@Repository 标记在数据访问层的类注册为Bean组件

@Componment 标记非三层的普通类注册为Bean组件

注:@Controller @Service @Repository 底层都继承 @Componment 注解

好处 增强可读性 更有利于Spring管理

注1:排除@Contorller注解

<context:component-scan base-package="com.kdy" >
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

1、type="annotation" 根据注解的完整限定名设置排除或包含

2、assignable 根据类的完整限定名设置排除\包含

后面了解即可

3、 type="aspectj" org.example..*Service+ 切面表达式 根据切面表达式设置排除或包括

4、regex 根据正则表达式设置包含\排除

5、custom 根据接口设置排除或包含

注2: 包含扫描

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

</context:component-scan>

use-default-filters="true" 为默认值 默认所有的都扫描

包含扫描 需要配合 use-default-filters="false"使用

<context:component-scan base-package="com.kdy" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

注解规则 会 自动将 类名首字母小写 作为 Bean的名字

使用注解的方式注入值

@Value("张三") private String name;

还可以使用


<context:property-placeholder location="db.properties"></context:property-placeholder>
@Value("${mysql.user}")
@Value("#{user.name}")

通过注解方式 自动 注入

@Autowired
UserService userService;

@Autowired 默认使用类型匹配;当类型匹配到多个 再使用名字去匹配。如果名字也没有匹配到则会报错

@Autowired 属性 方法 构造器上面


设置Bean的名字

@Service("userService")

通过设置@Quailfier("") 设置寻找的Bean

@Autowired
@Qualifier("userServiceImpl")
UserService userService;

同类型设置优先级

@Service
@Primary
public class UserServiceImpl implements UserService {

还可以使用泛型作为自动注入限定符


public interface BaseService<T> {
    T  getBean();

    void getUser();
}
@Service 
public class UserServiceImpl implements BaseService<User> {
@Autowired
    UserDao userDao;

    public void  getUser(){
        userDao.getUser();
    }

    @Override
    public User getBean(){
        return null;
    }
}

@Controller
public class UserController {


    @Autowired
    BaseService<User> userService;

    public void getUser(){
        userService.getUser();
    }

}

除了@AutoWire还可以使用 @Resource 来自动注入

依赖JDK:

import javax.annotation.Resource;

AutoWire 依赖Spring

import org.springframework.beans.factory.annotation.Autowired;

Resource 优先根据名字匹配
AutoWire 优先根据类型匹配

通过@Dependson 改变加载顺序

@Component
@DependsOn("user")
public class Role {

通过@Lazy设置懒加载

@Component
@Lazy
public class Role {

设置单例及多例模式

@Scope("singleton")   //默认值  单例
@Scope("prototype")   //多例

通过注解方式设置初始化及销毁

@PostConstruct
public void initMethod(){
    System.out.println("Role初始化");
}
@PreDestroy
public void desMethod(){
    System.out.println("Role销毁");
}