IOC常用的注解
@Component |
@Controller |
@Service |
@Repository |
DI常用的注解
@Autowired | 自动装配 |
@Qualifier | 自动装配 |
@Resource | 自动装配 |
@Inject | 根据类型自动装配 |
@Value | 基本类型和String类型赋值 |
@Scope | bean的作用范围注解 |
XML实现
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.hgd.spring.service"/>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="userService" class="com.hgd.spring.service.UserServiceImpl">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
@Component
public class UserServiceImpl implements UserService {
private String driver;
private String url;
private String username;
private String password;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Test
public void save() {
System.out.println(driver);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
}
//测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class DemoTest {
@Autowired
private UserService userService;
@Test
public void hello(){
userService.save();
}
}
XML和注解实现
@Component
public class UserServiceImpl implements UserService {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Test
public void save() {
System.out.println(driver);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
}