在applicationContext.xml中引入context约束
public class UserDaoImpl implements UserDao { @Override public void sayHello() { System.out.println("Hello Spring..."); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "> <!-- 指定扫描cn.itcast.dao包下的所有类中的注解. 注意:扫描包时,会扫描指定包下的所有子孙包 --> <context:component-scan base-package="cn.itcast.dao"></context:component-scan> </beans>
@Component(value="userDao") public class UserDaoImpl implements UserDao { @Override public void sayHello() { System.out.println("Hello Spring..."); } }
@Test public void demo1() throws Exception { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) applicationContext.getBean("userDao"); userDao.sayHello(); }
该组件作用在类上,spring还提供了@Component的三个衍生注解(功能目前来讲是一致的)
这三个注解是为了让标注类本身的用途清晰。
/** * 将对象注册到容器中 */ @Repository("userDao") // @Component(value="userDao") // @Component("userDao")就相当于在xml中配置<bean name="userDao" class="cn.itcast.dao.impl.UserDaoImpl") public class UserDaoImpl implements UserDao {
【值类型注入】@Value
@Value("18") private Integer age;
@Value("lisi") public void setName(String name) { this.name = name; }
【引用类型注入】
// @Autowired // 问题:如果匹配多个类型一致的对象,将无法选择具体注入哪一个对象 // @Qualifier("car2") //使用@Qualifier注解告诉spring容器自动装配哪个名称的对象 @Resource(name="car") private Car car;
@Scope(scopeName="singleton")
XML和注解:
原文:https://www.cnblogs.com/yft-javaNotes/p/10293699.html