Spring original annotations
annotation | Description |
---|---|
@Component | Used on the class to instantiate Bean |
@Controller | Used on the class to instantiate Bean (with web layer semantics) |
@Service | Used on the class to instantiate Bean (with service layer semantics) |
@Repository | Used on the class to instantiate Bean (with dao layer semantics) |
@Autowired | Inject reference types |
@Qualifier | Inject reference types |
@Resource | Inject reference types |
@Value | Inject basic types |
@Scope | Bean scope configuration |
@PostConstruct | Bean life cycle configuration (called upon initialization) |
@PreDestroy | Bean life cycle configuration (called when it is destroyed) |
Configure component scanning
Component scanning is configured in applicationContext.xml, which tells Spring to scan the annotations under the package and its sub-packages
Note: The configuration component scan needs to be performed under the context namespace, so don’t forget to add the context namespace (and its constraint path)
<!-- 配置组件扫描 -->
<context:component-scan base-package="service" />
<context:component-scan base-package="dao" />
@Component is used to instantiate Bean
@Component("userDao")
public class UserDaoImpl implements UserDao {
public void sayHi() {
System.out.println("Hello!!!");
}
}
@Controller/@Service/@Repository is also used to instantiate Bean with semantics
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void sayHi() {
System.out.println("Hello!!!");
}
}
@Autowired automatically injects references based on the class name (if the class has multiple beans in the spring container, an error will be reported)
@Component("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public void sayHi() {
userDao.sayHi();
}
}
@Autowired+@Qualifier injects references according to id (two together, no less writing)
@Component("userService")
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userDao")
private UserDao userDao;
public void sayHi() {
userDao.sayHi();
}
}
@Resource injects references based on id (completely equivalent to @Autowired+@Qualifier)
@Component("userService")
public class UserServiceImpl implements UserService {
@Resource(name = "userDao")
private UserDao userDao;
public void sayHi() {
userDao.sayHi();
}
}
@Value injects basic data types (usually used in conjunction with SPEL syntax)
<!-- 在applicationContext.xml引入properties资源文件,就将这些键值对“倒入”了spring容器中 -->
<context:property-placeholder location="classpath:xxx.properties" />
@Component("userService")
public class UserServiceImpl implements UserService {
@Value("root")
private String username;
@Value("${password}")
private String password;
// ...
}
@Scope configuration scope (singleton singleton/prototype multiple cases)
@Component("userDao")
@Scope("prototype")
public class UserDaoImpl implements UserDao {
// ...
}
@PostConstruct/@PreDestroy configuration life cycle (method automatically called during initialization/destroy)
@Component("userDao")
public class UserDaoImpl implements UserDao {
@PostConstruct
public void init() {
System.out.println("初始化时调用我 >_<");
}
// ...
@PreDestroy
public void destroy() {
System.out.println("销毁时调用我 >_<");
}
}
Spring new annotations
The classic annotations above cannot completely replace the xml configuration file. For example, the following situation:
- Non-custom Beans (Beans directly provided by third parties):
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">...</bean>
- Load the resource file:
<context:property-placeholder location="xxx.properties" />
- Configure component scanning:
<context:component-scan base-package="xxx" />
- Sub-module development:
<import resource="applicationContext-xxx.xml" />
We use some clever ideas and designs to solve the above problems:
- No longer configure in applicationContext.xml, but transfer these configurations to the config.SpringConfiguration.class class
- SPEL syntax can be used in applicationContext.xml, but the java code in the config.SpringConfiguration.class class obviously cannot be used. We can solve this problem ingeniously- Java code cannot use SPEL, but annotations can use SPEL; therefore, key-value pair information can be injected into member variables through annotations, and we can use these key-value pair information indirectly
- In the end, applicationContext.xml is completely obsolete and
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
replaced withApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
annotation | Description |
---|---|
@Configuration | Mark that this is a Spring configuration class |
@Bean | The marked return value will be directly placed in the Spring container |
@PropertySource | Used to load resource files |
@ComponentScan | Used to configure component scanning |
@Import | For sub-module development |
@Configuration // 表明这是一个配置类
@ComponentScan({
"dao", "service"}) // 配置组件扫描
@PropertySource("classpath:jdbc.properties") // 加载资源文件
@Import({
xxxConfiguration.class, xxxConfiguration.class}) // 分模块开发
public class SpringConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}