spring分为基于配置的开发和注解的开发两种方式
基于配置的方式是这样的:
<?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
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 包扫描、只要标注了@Controller、@Service、@Component、@Repository -->
<context:component-scan base-package="com.tl"></context:component-scan>
<bean id="person" class="com.tl.bean.Person">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
</beans>
基于配置文件的方式,我们可以这样去获取bean
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person1 = applicationContext.getBean("person", Person.class);
System.out.println(person1);
}
}
基于注解的方式如下:
@Configuration
告诉spring这是一个配置类
@Bean
给容器注册一个Bean
//配置类==配置文件
@Configuration //告诉spring这是一个配置类
public class MainConfig {
//给容器中注册一个Bean;类型为返回值的类型,id默认用方法名作为id
@Bean(value = "person")
public Person person01() {
return new Person("23", "李四");
}
}
基于注解的方式,我们可以这样去获取bean
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println(applicationContext.getBean(Person.class));
}
}