Spring_注解
Spring原始注解主要替代配置
注解 | 说名 |
---|---|
@Component | 使用在类上用于实例化Bean |
@Controller | 使用在web层类上用于实例化Bean |
@Service | 使用在service类层上用于实例化Bean |
@Repository | 使用在dao层上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifier,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 注入Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法是Bean的初始化方法(init) |
@PreDestroy | 使用在方法上标注该方法是Bean的销毁方法(destroy) |
applicationContext.xml
xmlns:context="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 http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置组件扫描-->
<context:component-scan base-package="com.lzy"></context:component-scan>
实例
userDao
package com.lzy.dao.impl;
import com.lzy.dao.UserDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
//<bean id="userDao" class="com.lzy.dao.impl.UserDaoImpl"></bean>
//@Component ("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void save(){
System.out.println("save running....");
}
}
userService
package com.lzy.service.impl;
import com.lzy.dao.UserDao;
import com.lzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
//<bean id="userService" class="com.lzy.service.impl.UserServiceImpl">
//<property name="userDao" ref="userDao"></property>
//</bean>
//@Component("userService")
@Service("yserService")
public class UserServiceImpl implements UserService {
//使用注解的方式可以省略方法
@Autowired
@Qualifier("userDao")//按照id值注入,若按照类型注入时可以省略不写(必须结合Autowired注解)@Resource(name"")注解可单独使用需引入javax.annotation-api
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
public void save(){
System.out.println("userService running...");
userDao.save();
}
}
web
package com.lzy.web;
import com.lzy.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserController {
public static void main(String[] args){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
}