为了账号安全,请及时绑定邮箱和手机立即绑定

Spring基础使用(二)-------Bean的注解方式装配

标签:
Java SpringBoot

1、常用注解

  • @Component:通用注解
  • @Repository:一般用于注解持久化层的类
  • @Service:一般用于注解Service类
  • @Controller:一般用于注解控制器类。
  • @Named:与@Component用法相同。

  • @Autowired:注入对象,用于修饰成员,set方法和构造方法。
  • @Resource:与@Autowired用法相同
  • @Inject:与@Autowired用法相同
  • @Required:修饰set方法,作用与@Autowired相同,注入对象

  • @Configuration:声明Bean的配置,与@Bean一起使用。
  • @Bean:声明Bean,与xml中使用<bean></bean>效果相同,与@Configuration一起使用

  • @ImportResource:加载包含配置文件信息的xml文件,与@Value一起使用。
  • @Value:获取@ImportResource处理的配置文件中的配置项,与@ImportResource一起使用。

  • @PostConstruct:表示被修饰的方法为bean初始化回调方法。
  • @PreDestroy:表示被修饰的方法为bean销毁回调方法。

  • @Scope:标识作用域和代理方式,可以配置@Componment或者@Bean使用

2、XML文件格式及Bean扫描

使用 <context:component-scan base-package=""/>或者<context:annotation-config>指定Bean的自动检测范围。

<context:component-scan base-package=""/>能够处理类的注解,功能更强大,并且能够完全覆盖后者。

<?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">
    <!--指定Bean扫描的范围-->
    <context:component-scan base-package="service"/>
</beans>

在xml文件中可以通过include和exclude进行自定义扫描,<context:component-scan base-package=""/>节点允许有两个子节点<context:include-filter type="" expression=""/><context:exclude-filter type="" expression=""/>

使用<context:include-filter type="" expression=""/>时,一定要在<context:component-scan base-package=""/>中设置属性use-default-filters=false

<context:component-scan base-package="service" use-default-filters="false">
        <context:include-filter type="" expression=""/>
        <context:exclude-filter type="" expression=""/>
    </context:component-scan>

关于type的值,可以参考Spring官网的描述:
图片描述

3、Bean对象的命名

使用注解可以显示指定Bean对象的名称,如果没有指定,则使用BeanNameGenerator自动生成的名称。

@Component("hello")
public class HelloServiceImpl implements HelloService
{
    public void serviceSave(String arg){
        System.out.println("输入数据是:" + arg);
    }
}

可以自定义命名策略,条件是实现BeanNameGenerator接口(需要包含无参构造函数),并在XML中进行指定。

package service;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;

public class MyNameGenerator implements BeanNameGenerator {
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        return definition.getBeanClassName().toUpperCase();
    }

    public MyNameGenerator() {
    }
}
<context:component-scan base-package="service" name-generator="service.MyNameGenerator"/>

4、Bean的作用域

使用注解:@Scope("")

@Component
@Scope("prototype")
public class HelloServiceImpl implements HelloService
{
}

可以自定义scope策略,条件是实现ScopeMetadataResolver接口(需要包含无参构造函数),并在XML中指定。

public class MyScopeMetadataResolver implements ScopeMetadataResolver {
    public ScopeMetadata resolveScopeMetadata(BeanDefinition beanDefinition) {
        ScopeMetadata metadata = new ScopeMetadata();
        ...
        return metadata;
    }

    public MyScopeMetadataResolver() {
    }
}
<context:component-scan base-package="service" scope-resolver="service.MyScopeMetadataResolver"/>

5、@Required和@Autowired

@Required注解用来修饰set方法,表示受影响的Bean必须在配置时候被设置。

@Autowired注解使用范围更大,可以修饰成员变量,或者set方法或者构造方法,实现的效果是相同的。如果找不到对应的Bean,会注入失败抛出异常,可以通过设置@Autowired中required=false来避免。

@Autowired(required = false)

@Autowired可以修饰集合或者数组。当修饰集合或者数组的时候,Spring会将ApplicationContext中所有对应类型的Bean注入进去。当类中依赖抽象的集合的时候,这种机制可以将所有实现该接口的对象注入到集合中。对于List集合,可以通过在对应Bean上使用@Order注解保证集合中的顺序。

@Repository
@Order(1)
public class DAOImpl implements DAO {
    public void DAOSave(String arg) {
    }
}
@Repository
@Order(2)
public class DAOImplBak implements DAO {
    public void DAOSave(String arg) {
    }
}
@Component
public class HelloServiceImpl implements HelloService
{
    @Autowired
    private List<DAO> daos;

    public void serviceSave(){

        for (DAO dao : daos)
        {
            System.out.println(dao.getClass().getName());
        }
    }
}
learn.DAO.DAOImpl
learn.DAO.DAOImplBak

Process finished with exit code 0

@Autowired修饰抽象成员的时候,配合使用@Qualifier注解,指定被注入的对象的名称。

    @Autowired
    @Qualifier("DAOImplBak")
    private DAO dao;

6、@Bean

@Bean注解配合@Configuration,能够实现在java代码中,做到与xml配置<bean>一样的效果。

@Configuration
public class ServiceConfig {

    @Bean(name = "ttService", initMethod = "init", destroyMethod = "dest")
    public TestService testService()
    {
        return new TestService();
    }
}
public class TestService {

    public void init()
    {
    }

    public void dest()
    {
    }
}

上述代码等同的效果,就是在xml文件中做出如下配置

    <bean id="ttService" class="learn.service.TestService" init-method="init" destroy-method="dest"></bean>

@Bean注解可以用于自定义实现的processer。

使用@Bean注解定义Bean的时候,可以配合使用@Scope,指定Bean的作用域和代理方式。

7、@ImportResource和@Value注解进行配置文件的加载和使用

@ImportResource和@Value注解主要用于配置文件的加载和使用。通过@ImportResource注解指定配置文件的路径,使用@Value注解使用配置文件中的具体配置。

加载配置文件有2中方式,一种是直接通过xml文件进行加载和使用;另外一种是通过注解方式。

通过xml加载和使用:

    <context:property-placeholder location="classpath:/db.properties"/>
    <bean name="databaseConfig" class="learn.service.DatabaseConfig">
        <property name="ipAddress" value="${db.ip}"/>
        <property name="userName" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="port" value="${db.port}"/>
    </bean>

通过注解方式加载和使用:

configuration.xml文件中添加placeholder配置:

<context:property-placeholder location="classpath:/db.properties"/>

在代码中,通过@ImportResource注解指定placeholder所在的xml文件

@Configuration
@ImportResource("classpath:configuration.xml")
public class Config {
    @Value("${db.username}")
    private String userName;

    @Value("${db.password}")
    private String password;

    @Value("${db.ip}")
    private String ipAddress;

    @Value("${db.port}")
    private int port;

    @Bean
    public DatabaseConfig databaseConfig()
    {
        return new DatabaseConfig(userName, ipAddress, port, password);
    }
}

8、@Resource注解使用方式与@Autowired使用方式相同

9、@PostConstruct和@PreDestroy

@PostConstruct和@PreDestroy修饰函数,表示bean的初始化回调方法和销毁回调方法。与xml配置方式中指定init-methoddestroy-method的效果是相同的。

    @PostConstruct
    public void init()
    {}

    @PreDestroy
    public void destroy()
    {}

10、@Inject注解

@Inject与@Autowired是等效的,用于类,属性,set方法,构造器。

10、@Named注解

@Named与@Component是等效的,用于修饰类。

点击查看更多内容
5人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1万
获赞与收藏
1426

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消