准备工作
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();
}
}
持续更新中......
网友评论