在使用Spring容器管理我們項目的時候,我們可以使用xml的方式或者注解的方式。二者适用的場景分别是Bean來自第三方和Bean由開發者自己實作。 我們可以根據不同情況使用不同的方式。這裡主要對注解方式進行說明.
其中5.Spring的新注解和前面4節的注解功能是一樣的。但是不再使用前4節所說的注解來配置,而是引入了配置類的概念,和我們寫xml也是一樣的。在配置類中的内容,你都可以翻譯成前4節所說的注解,或者xml檔案。
文章目錄
- 1.用于建立對象的注解
-
- 1.1 @Component
- 1.2 @Controller @Service @Repository
- 2.用于注入資料的注解
-
- 2.1 @Autowired
- 2.2 @Qualifier
- 2.3 @Resource
- 2.4 @Value
- 3.用于指定作用範圍的注解
-
- 3.1 @Scope
- 4.用于生命周期的注解
-
- 4.1 @PostConstruct
- 4.2 @PreDestroy
- 5.Spring的新注解
-
- 5.1 @Configuration
- 5.2 @ComponentScan
- 5.3 @Bean
- 5.4 @PropertySource
- 5.5 @Import
1.用于建立對象的注解
相當于
<bean id="" class="">
1.1 @Component
作用:
把資源讓spring來管理。相當于在xml中配置一個bean。
屬性:
value:指定bean的id。如果不指定value屬性,預設bean的id是目前類的類名,并且首字母小寫。
示例
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
public void saveAccount(){
}
}
1.2 @Controller @Service @Repository
他們三個注解都是針對
@Component
的衍生注解,他們的作用及屬性都是一模一樣的,隻不過是提供了更加明确的語義化。
-
:一般用于表現層的注解。@Controller
-
:一般用于業務層的注解。@Service
-
:一般用于持久層的注解。@Repository
細節:如果注解中有且隻有一個屬性要指派時,且名稱是value,value在指派是可以不寫。
2.用于注入資料的注解
相當于:
<property name="" ref="">
或者
<property name="" value="">
在類中使用這些注解還有一個好處就是,不用像我們在類中一樣,需要擷取容器。而是直接将需要的Bean注入即可。比如如果不使用注解的話,你可能需要在類中這樣寫,以此來擷取AccountService執行個體對象:
public class AccountServiceTest {
private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
private IAccountService as = ac.getBean("accountService",IAccountService.class);
}
2.1 @Autowired
作用:
自動按照類型注入。當使用注解注入屬性時,set方法可以省略。它隻能注入其他bean類型。當有多個類型比對時,使用要注入的對象變量名稱作為bean的id,在spring容器查找,找到了也可以注入成功。找不到就報錯。
示例
public class AccountServiceImpl implements IAccountService {
//如果容器中有多個IAccountDao類型的Bean,則按照accountDao來查找,查找不到則報錯
@Autowired
private IAccountDao accountDao;
public void saveAccount(){
accountDao.saveAccount();
}
}
2.2 @Qualifier
作用:
在自動按照類型注入的基礎之上,再按照Bean的id注入。它在給字段注入時不能獨立使用,必須和@Autowire一起使用;但是給方法參數注入時,可以獨立使用。
屬性:
value:指定bean的id。
示例
public class AccountServiceImpl implements IAccountService {
//按照accountDao到容器中查找Bean
@Autowired
@Qualifier("accountDao")
private IAccountDao ad;
public void saveAccount(){
ad.saveAccount();
}
}
2.3 @Resource
作用:
直接按照Bean的id注入。它隻能注入其他bean類型(而不是普通資料類型和String)。相當于上面兩個标簽的共同作用
屬性:
name:指定bean的id。
示例
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao ad;
public void saveAccount(){
ad.saveAccount();
}
}
2.4 @Value
作用:
以上三個注解隻能注入Bean類型資料,而不能注入普通類型,并且集合類型隻能使用XML來注入,而@Value是用來注入基本資料類型和String類型資料的 ,并且支援使用spEL(Spring EL表達式${})
屬性:
value:用于指定值
示例:
public class AccountServiceImpl implements IAccountService {
@Value("value")
private String str;
public void saveAccount(){
}
}
3.用于指定作用範圍的注解
相當于:
<bean id="" class="" scope="">
中的scope
3.1 @Scope
作用:
指定bean的作用範圍。
屬性:
value:指定範圍的值。 取值:
- singleton 單例,預設
- prototype 多例
- request
- session
- globalsession
例子:
@Component("accountService")
@Scope("prototype")
public class AccountServiceImpl implements IAccountService {
public void saveAccount(){
}
}
4.用于生命周期的注解
相當于:
<bean id="" class="" init-method="" destroy-method="" />
中的init-method和destroy-method
4.1 @PostConstruct
作用:
用于指定初始化方法。
4.2 @PreDestroy
作用:
用于指定銷毀方法。
例子:
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
public void saveAccount(){
}
@PostConstruct
public void init(){
}
@PreDestroy
public void destroy(){
}
}
5.Spring的新注解
5.1 @Configuration
作用:
用于指定目前類是一個spring配置類,當建立容器時會從該類上加載注解。擷取容器時需要使用AnnotationApplicationContext(注解類.class)。 如果是使用AnnotationApplicationContext來引入或者被其他配置類導入(5.5 @Import),可以不用寫這個标簽。
屬性:
value:用于指定配置類的位元組碼
示例:
@Configuration
public class SpringConfiguration {
}
5.2 @ComponentScan
作用:
用于指定spring在初始化容器時要掃描的包。作用和在spring的xml配置檔案中的:
<context:component-scan base-package="com.itheima"/>
是一樣的。
屬性:
basePackages:用于指定要掃描的包。和該注解中的value屬性作用一樣。
示例:
@Configuration
@ComponentScan("com.itheima")
public class SpringConfiguration {
}
5.3 @Bean
作用:
該注解隻能寫在方法上,表明使用此方法建立一個對象,并且放入spring容器。可以在方法上使用@Scope來訓示作用範圍。
屬性:
name:給目前@Bean注解方法建立的對象指定一個名稱(即bean的id)。當不寫時,預設值是目前方法的名稱。當有參數的時候和@Autowired的方式是一樣的
示例(有參數和無參數):
public class JdbcConfig {
/**
* 用于建立一個QueryRunner對象
* @param dataSource
* @return
*/
@Bean(name="runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 建立資料源對象
* @return
*/
@Bean(name="ds1")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring_day02");
ds.setUser("root");
ds.setPassword("1234");
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 建立資料源對象
* @return
*/
@Bean(name="ds2")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring_day02");
ds.setUser("root");
ds.setPassword("1234");
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
5.4 @PropertySource
作用:
用于加載.properties檔案中的配置。例如我們配置資料源時,可以把連接配接資料庫的資訊寫到properties配置檔案中,就可以使用此注解指定properties配置檔案的位置。
屬性:
value[]:用于指定properties檔案位置。如果是在類路徑下,需要寫上classpath:
示例:
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 用于建立一個QueryRunner對象
* @param dataSource
* @return
*/
@Bean(name="runner")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 建立資料源對象
* @return
*/
@Bean(name="ds")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
jdbcConfig.properties檔案内容
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=1234
5.5 @Import
作用:
用于導入其他配置類,在引入其他配置類時,其他配置類可以不用再寫@Configuration注解。當然,寫上也沒問題。
屬性:
value[]:用于指定其他配置類的位元組碼。
示例:
@Import(JdbcConfig.class)
public class SpringConfiguration {
}