美文网首页
Spring常用注解配置

Spring常用注解配置

作者: iris_YanZhang | 来源:发表于2018-08-10 16:33 被阅读0次

准备工作

applicationContext.xml 添加命名空间和约束,适用于xml和注解同时使用

xmlns:context="http.springframework.org/schema/context"
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd

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

常用注解

对象注入

一般写在类名前

@Conponent

@Component("id名"),可以不指定,默认为类名首字母小写
Spring中的任何资源,Bean

@Controller

分层注解,表现层

@Service

业务层

@Repository

持久层

属性注入

@Value

@Value("...")

适用于基本类型,String的属性

@Autowired

@Autowired
private Xxx xxx

Bean的注入,只看Bean的类型,不看id(只要类型一致,不管哪个Bean都注入)

@Qualifier

@Autowired
@Qualifier("...")
private Xxx xxx

与Autowired联合用 ,@Autowired指定类型,@Qualifier指定id

@Resource

@Resource(name="...")

可以替代上一个

初始化/销毁

@PostConstruct

Bean被初始化时的方法,不是构造方法

@PreDestroy

作用域

@Scope

@Component("...")
@Scope("prototype")
public class Xxx
}

主要作用域有singleton和prototype

配置类

@Configuration

注明一个类是一个配置类,一般是applicationContext.xml的替代类

@ComponentScan

指定扫描的包@ComponentScan("xxx.xxx")

@Bean

就是Bean,只用于方法上;可以指定Bean的id,@Bean(name="...")

@Import

引入已有的配置类@Import(value="...")
引入类可以不用@Configuration标记

@PropertySource

引入属性文件到config类中

example

@Configuration
@ComponentScan("...")
@Import(value="JdbcConfig.class")
@PropertySource("jdbc.property")
public class SpringConfig{
    //4.3之后不再需要
    @Bean
    public PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
}

持续更新中......

相关文章

  • Spring(二) 注解

    Spring(二) 注解 Spring中常用注解介绍 Spring中的注解配置和xml配置要实现的功能是一样的 注...

  • Spring系列常用注解

    附录史上最全Spring注解Spring常用注解Springboot常用45注解Springboot常用27个注解...

  • Java面试题之Spring(二)

    Spring常用的注解? spring 在2.5版本以后开始支持注解的方式来配置依赖注入,可以用注解的方式...

  • Spring 注解使用

    常用注解 Spring中有三种配置方式:基于XML的配置、基于注解的配置、基于Java的配置。 使用原则: 1、S...

  • 六、Spring的Bean管理(注解方式)

    6.1 、配置注解扫描 6.2、在相关类上添加注解 6.3、spring的bean管理常用注解 6.3.1、@Co...

  • spring常用注解

    spring常用注解 Value : 从配置文件中注入变量ConfigurationProperties(boot...

  • Spring注解

    Spring常用注解 @Configuration:表明当前java类是一个配置类 @ImportResource...

  • 04【掌握】常用注解[spring的java配置]

    04【掌握】常用注解[spring的java配置] 1. 相关注解说明 1、@Configuration作用于类上...

  • Spring常用注解配置

    准备工作 applicationContext.xml 添加命名空间和约束,适用于xml和注解同时使用 常用注解 ...

  • Spring常用注解配置

    IOC相关 首先要在配置文件中启用注解扫描: 标签负责扫描哪些...

网友评论

      本文标题:Spring常用注解配置

      本文链接:https://www.haomeiwen.com/subject/onhlbftx.html