注解注入
1.@Component
(1)定义
创建对象,等同于<bean></bean>功能
(2)创建maven工程
略
(3)pom
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
(4)entity并加入注解
package cn.kgc.entity;
import org.springframework.stereotype.Component;
@Component(value = "myUser")
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(5)applicationContext.xml加入组件扫描器
<?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: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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc.entity"/>
</beans>
(6)测试类TestSpring
package cn.kgc.test;
import cn.kgc.entity.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void testdemo001(){
String conf = "applicationContext.xml";
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(conf);
User myUser = (User) ac.getBean("myUser");
System.out.println(myUser);
}
}
(7)拓展
第一种拓展:@Component( "myUser")
第二种拓展:@Component
2.@Repository
(1)定义
用在持久层上面,方法在dao的实现类上面,表示创建dao对象
(2)核心代码UserMapper.java
public interface UserMapper {
public Integer addUser();
}
(3)核心代码UserMapperImpl.java
@Repository(value = "userMapper") //在申明XXMapper的bean对象的时候,@Respository中的value不建议省略
public class UserMapperImpl implements UserMapper{
@Override
public Integer addUser() {
System.out.println("调用持久层方法....");
return 0;
}
}
(4)核心代码applicationContext.xml
<?xml version="1.0" en