Spring常用注解配置

准备工作

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();
    }
}

持续更新中……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值