使用注解生成bean对象
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<context:component-scan base-package="mySpringStart.demoOfBean" ></context:component-scan>
</beans>
@Component
public class UserService {
@Value("Hello Spring!!!")
private String name;
public void show(){
System.out.println(name);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1 = (UserService) context.getBean("userService");
System.out.println(userService1);
userService1.show();
}
使用xml配置 生成bean对象
<bean id="userService" class="mySpringStart.demoOfBean.UserService">
<property name="name" value="root"/>
</bean>
<!-- <context:component-scan base-package="mySpringStart.demoOfBean" ></context:component-scan> -->
</beans>
public class UserService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
@Test
public void test1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
UserService userService2 = applicationContext.getBean(UserService.class);
System.out.println(userService);
System.out.println(userService2);
}