網(wǎng)站管理員是什么意思湖南專業(yè)seo推廣
目錄
一、使用注解開發(fā)的前提
1.1 配置注解掃描路徑
二、使用注解創(chuàng)建對象
2.1 @Controller(控制器儲存)
2.2 @Service(服務儲存)
2.3 @Repository(倉庫儲存)
2.4 @Component(組件儲存)
2.5 @Configuration(配置儲存)
2.6 為什么要這么多類注解
2.7 方法注解@Bean
一、使用注解開發(fā)的前提
經(jīng)歷過了Spring的配置文件創(chuàng)建對象之后,我們發(fā)現(xiàn)這個方法其實還是有點麻煩,那么有什么更好的方法去創(chuàng)建對象嘛?有!注解的方式創(chuàng)建對象
1.1 配置注解掃描路徑
在使用注入創(chuàng)建對象的時候,首先就需要在Spring的配置文件中去配置注解的掃描路徑,注意這個配置文件中的其他東西一定要正確不然可能會報一些莫名其妙的錯
<?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:content="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 https://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置注解的掃描路徑--><content:component-scan base-package="com.gl.demo"/>
</beans>
這里需要注意的是,你配置的包掃描路徑是有范圍限制的,我這里配置的到demo包底下,如果我還有一個包不在demo包底下,那么這個包下面的注解都是不會生效的
二、使用注解創(chuàng)建對象
在配置文件中配置了包掃描路徑之后,我們就可以開始使用注解創(chuàng)建對象的方式來替代在配置文件中創(chuàng)建對象的方式了。接下來將介紹幾種常用的注解
- 類注解:@Controller、@Service、@Repository、@Component、@Configuration
- 方法注解:@Bean
????就是通過這幾個注解,代替了原來配置文件中的標簽
2.1 @Controller(控制器儲存)
類注解顧名思義就是在類上面添加注解
@Test
public void test() {ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");UserController userController = ctx.getBean("userController",UserController.class);userController.sayHi("張三");
}
接下來通過Spring的配置工廠來獲取對象
@Test
public void test() {ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");UserController userController = ctx.getBean("userController",UserController.class);userController.sayHi("張三");
}
這里可以可以發(fā)現(xiàn)即使配置文件中沒有寫bean標簽也可以創(chuàng)建出對象了,由于后面的類注解方式也是一樣的就不多解釋了
2.2 @Service(服務儲存)
@Service
public class UserService {public void sayHi(String name) {System.out.println("Hi," + name);}
}
2.3 @Repository(倉庫儲存)
@Repository
public class UserRepository {public void sayHi(String name) {System.out.println("Hi," + name);}
}
2.4 @Component(組件儲存)
@Component
public class UserComponent {public void sayHi(String name) {System.out.println("Hi," + name);}
}
2.5 @Configuration(配置儲存)
@Configuration
public class UserConfiguration {public void sayHi(String name) {System.out.println("Hi," + name);}
}
2.6 為什么要這么多類注解
其實這個注解在底層的實現(xiàn)方式都是一樣的,那為什么搞出這么多呢?這是為了代碼的可讀性!什么層用什么注解一目了然。還要注意的是,這里的類名就是之前配置文件中的id值,所以我們可以直接通過類名首字母小寫的方式獲取到對象,如果類名是兩個大寫字母開頭那就使用原類名獲取對象
2.7 方法注解@Bean
這里的@Bean就是原來的在配置文件中的Bean標簽,所以當我們的方法返回一個對象的時候就可以使用這個@Bean注解,同時方法名就是原來配置文件中的id值。最后也是最重要的一點就是,這個方法注解需要搭配類注解一起使用
@Component
public class Users {@Beanpublic User user1() {User user = new User();user.setId(1);user.setName("Java");return user;}
}
public void test() {ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");User user = (User) context.getBean("user1");System.out.println(user.toString());
}