Java Code Examples for org.springframework.context.ApplicationContext#getBean()
The following examples show how to use
org.springframework.context.ApplicationContext#getBean() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestApp.java From newblog with Apache License 2.0 | 6 votes |
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:bean-*.xml"); System.out.println(context); HttpService httpService = context.getBean("httpService", HttpService.class); System.out.println(httpService); try { // Map<String, String> maps = new HashMap<String, String>(); // maps.put("wd", "java"); // String string = httpService.doGet("http://www.baidu.com/s"); // System.out.println(string); Map<String, Object> maps = new HashMap<String, Object>(); maps.put("wd", "java"); String string = httpService.doPost( "http://localhost:8080/ssss/HaHaServlet", maps); System.out.println(string); } catch (Exception e) { e.printStackTrace(); } }
Example 2
Source File: SofaBootRpcSpringUtil.java From sofa-rpc-boot-projects with Apache License 2.0 | 6 votes |
/** * 根据配置的ref获得真正的spring bean * * * @param beanRef spring ref * @param applicationContext spring上下文 * @param appClassLoader 业务上下文 * @return 业务bean */ public static Object getSpringBean(String beanRef, ApplicationContext applicationContext, ClassLoader appClassLoader, String appName) { Object object = null; if (StringUtils.hasText(beanRef)) { if (applicationContext == null) { LOGGER.error("get bean from spring failed. beanRef[" + beanRef + "];classLoader[" + appClassLoader + "];appName[" + appName + "]"); } else { object = applicationContext.getBean(beanRef); } } return object; }
Example 3
Source File: H2cClientApplication.java From sofa-rpc-boot-projects with Apache License 2.0 | 6 votes |
public static void main(String[] args) { //change port to run in local machine System.setProperty("server.port", "8081"); SpringApplication springApplication = new SpringApplication(H2cClientApplication.class); ApplicationContext applicationContext = springApplication.run(args); H2cService directService = (H2cService) applicationContext.getBean("h2cServiceReference"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } String result = directService.sayH2c("h2c"); System.out.println("invoke result:" + result); if ("h2c".equalsIgnoreCase(result)) { System.out.println("h2c invoke success"); } else { System.out.println("h2c invoke fail"); } }
Example 4
Source File: BootstrapTest.java From Spring with Apache License 2.0 | 5 votes |
@Test public void testStart6() { ApplicationContext ctx = new AnnotationConfigApplicationContext(DataSourceConfig1.class); DataSource dataSource = ctx.getBean("dataSource", DataSource.class); assertNotNull(dataSource); }
Example 5
Source File: ConvertingEncoderDecoderSupport.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Strategy method used to obtain the {@link ConversionService}. By default this * method expects a bean named {@code 'webSocketConversionService'} in the * {@link #getApplicationContext() active ApplicationContext}. * @return the {@link ConversionService} (never null) */ protected ConversionService getConversionService() { ApplicationContext applicationContext = getApplicationContext(); Assert.state(applicationContext != null, "Unable to locate the Spring ApplicationContext"); try { return applicationContext.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class); } catch (BeansException ex) { throw new IllegalStateException("Unable to find ConversionService: please configure a '" + CONVERSION_SERVICE_BEAN_NAME + "' or override the getConversionService() method", ex); } }
Example 6
Source File: ValidatorUtil.java From webcurator with Apache License 2.0 | 5 votes |
/** * Helper method to check to see if the Target of a target instance is approved for harvest. * @param aErrors the errors object to populate * @param aTargetInstanceOid the target instance to check * @param aErrorCode the error code for a vaildation failure */ public static void validateTargetApproved(Errors aErrors, Long aTargetInstanceOid, String aErrorCode) { ApplicationContext context = ApplicationContextFactory.getWebApplicationContext(); TargetInstanceManager tiManager = (TargetInstanceManager) context.getBean(Constants.BEAN_TARGET_INSTANCE_MNGR); TargetManager targetManager = (TargetManager) context.getBean(Constants.BEAN_TARGET_MNGR); TargetInstance ti = tiManager.getTargetInstance(aTargetInstanceOid); if (!targetManager.isTargetHarvestable(ti)) { // failure target is not approved to be harvested. Object[] vals = new Object[1]; vals[0] = ti.getTarget().getOid().toString(); aErrors.reject(aErrorCode, vals, "target instance is not approved for harvest"); } }
Example 7
Source File: DataFeedAPI.java From AIDR with GNU Affero General Public License v3.0 | 5 votes |
@GET @Produces("application/json") @Consumes("application/json") @Path(value = "/{code}/feeds") public List<DataFeedInfo> findbyCollectionCode(@PathParam("code") String code, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit){ offset = (offset != null) ? offset : Constants.DEFAULT_OFFSET; limit = (limit != null) ? limit : Constants.DEFAULT_RECORD_LIMIT; ApplicationContext appContext = new ClassPathXmlApplicationContext("spring/spring-servlet.xml"); DataFeedService dataFeedService = (DataFeedService) appContext.getBean("dataFeedService"); return dataFeedService.findbyCollectionCode(code, offset, limit); }
Example 8
Source File: Main.java From java-cheat with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); // This magically searches HelloWorldConfig // for a method that returns HelloWorld. HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.say(); }
Example 9
Source File: ScriptingDefaultsTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void defaultAutowire() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); ITestBean otherBean = (ITestBean) context.getBean("otherBean"); assertEquals(otherBean, testBean.getOtherBean()); }
Example 10
Source File: ComRdirUserForm.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
private ComDeviceService getDeviceService() { if (comDeviceService == null) { ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); comDeviceService = applicationContext.getBean(ComDeviceService.class); } return comDeviceService; }
Example 11
Source File: SpringResoucesTest.java From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Test public void testClassPathXmlApplicationContext3() { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/*.xml"); Person zhangsan = ctx.getBean("person_zhangsan", Person.class); Assert.assertNotNull(zhangsan); System.out.println(zhangsan); Person lisi = ctx.getBean("person_lisi", Person.class); Assert.assertNotNull(lisi); System.out.println(lisi); ((ClassPathXmlApplicationContext) ctx).close(); }
Example 12
Source File: SpringNamespaceWithAssignedDataSourceMain.java From sharding-jdbc-1.5.1 with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws SQLException { // CHECKSTYLE:ON ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/applicationContextWithAssignedDataSource.xml"); OrderService service = applicationContext.getBean(OrderService.class); service.insert(); service.select(); service.delete(); service.select(); ConfigService configService = applicationContext.getBean(ConfigService.class); configService.select(); }
Example 13
Source File: StorefrontApplication.java From yes-cart with Apache License 2.0 | 5 votes |
/** * Mount resources to particular paths. */ private void mountResources() { final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); final WicketResourceMounter mounter = ctx.getBean( "wicketResourceMounter", WicketResourceMounter.class); mounter.mountResources(this); }
Example 14
Source File: ValidatorUtil.java From webcurator with Apache License 2.0 | 5 votes |
/** * Helper method to check to see if the bandwidth percentage setting is * less than or equal to the maximum * @param aErrors the errors object to populate * @param aErrorCode the error code for a vaildation failure * @param aPercentage the percentage to check. */ public static void validateMaxBandwidthPercentage(Errors aErrors, int aPercentage, String aErrorCode) { ApplicationContext context = ApplicationContextFactory.getWebApplicationContext(); HarvestBandwidthManager harvestBandwidthManager = (HarvestBandwidthManager) context.getBean(Constants.BEAN_HARVEST_BANDWIDTH_MANAGER); if (aPercentage > harvestBandwidthManager.getMaxBandwidthPercent()) { // failure bandwidth percentage setting is too high. Object[] vals = new Object[1]; vals[0] = harvestBandwidthManager.getMaxBandwidthPercent(); aErrors.reject(aErrorCode, vals, "max bandwidth percentage exeeded"); } }
Example 15
Source File: GroovyScriptFactoryTests.java From spring-analysis-note with MIT License | 5 votes |
private void testMetaClass(String xmlFile) { // expect the exception we threw in the custom metaclass to show it got invoked try { ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile); Calculator calc = (Calculator) ctx.getBean("delegatingCalculator"); calc.add(1, 2); fail("expected IllegalStateException"); } catch (IllegalStateException ex) { assertEquals("Gotcha", ex.getMessage()); } }
Example 16
Source File: FeedbackTool.java From sakai with Educational Community License v2.0 | 5 votes |
public void init(ServletConfig config) throws ServletException { super.init(config); try { ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); sakaiProxy = (SakaiProxy) context.getBean("org.sakaiproject.feedback.util.SakaiProxy"); securityService = (SecurityService) context.getBean("org.sakaiproject.authz.api.SecurityService"); siteService = (SiteService) context.getBean("org.sakaiproject.site.api.SiteService"); } catch (Throwable t) { throw new ServletException("Failed to initialise FeedbackTool servlet.", t); } }
Example 17
Source File: UpdateMyUserRobotPreference.java From cerberus-source with GNU General Public License v3.0 | 5 votes |
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); IUserService userService = appContext.getBean(UserService.class); try { String ss_ip = ParameterParserUtil.parseStringParam(request.getParameter("ss_ip"), ""); String ss_p = ParameterParserUtil.parseStringParam(request.getParameter("ss_p"), ""); String platform = ParameterParserUtil.parseStringParam(request.getParameter("platform"), ""); String browser = ParameterParserUtil.parseStringParam(request.getParameter("browser"), ""); String version = ParameterParserUtil.parseStringParam(request.getParameter("version"), ""); User usr = userService.findUserByKey(request.getUserPrincipal().getName()); usr.setRobotHost(ss_ip); usr.setRobotPort(ss_p); usr.setRobotPlatform(platform); usr.setRobotBrowser(browser); usr.setRobotVersion(version); userService.updateUser(usr); ILogEventService logEventService = appContext.getBean(LogEventService.class); logEventService.createForPrivateCalls("/UpdateMyUserRobotPreference", "UPDATE", "Update user robot preference for user: " + usr.getLogin(), request); response.getWriter().print(usr.getLogin()); } catch (CerberusException myexception) { response.getWriter().print(myexception.getMessageError().getDescription()); } }
Example 18
Source File: StartHereApplication.java From java-starthere with MIT License | 5 votes |
public static void main(String[] args) { checkEnvironmentVariable("OAUTHCLIENTID"); checkEnvironmentVariable("OAUTHCLIENTSECRET"); if (!stop) { ApplicationContext ctx = SpringApplication.run(com.lambdaschool.starthere.StartHereApplication.class, args); DispatcherServlet dispatcherServlet = (DispatcherServlet) ctx.getBean("dispatcherServlet"); dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); } }
Example 19
Source File: SpringRiderTestContext.java From database-rider with Apache License 2.0 | 4 votes |
private static DataSource getDataSource(TestContext testContext, String beanName) { ApplicationContext context = testContext.getApplicationContext(); return beanName.isEmpty() ? context.getBean(DataSource.class) : context.getBean(beanName, DataSource.class); }
Example 20
Source File: LamsAuthoringFinishController.java From lams with GNU General Public License v2.0 | 2 votes |
/** * Find a tool's service registered inside lams. * * @param signature * the tool signature. * @return the service object from tool. * @throws NoSuchBeanDefinitionException * if the tool is not the classpath or the supplied service name is wrong. */ private Object findToolService(ApplicationContext applicationContext, String signature) throws NoSuchBeanDefinitionException { Tool tool = lamsToolService.getToolBySignature(signature); return applicationContext.getBean(tool.getServiceName()); }